I have a table with Boolean values (0 and 1 only) that needs to be CSV-ed to a client. I know I can do 1 replace like this:
SELECT REPLACE(email, '%40', '@'),
REPLACE(name,'%20', ' '),
REPLACE(icon_clicked, 1, 'Yes')
FROM myTable
WHERE id > 1000;
This will convert all the values of 1 to 'Yes', but how to do this in a single query for both 1 => Yes and 0 => No so Boolean result is stored in a single column? I tried to do this:
SELECT REPLACE(email, '%40', '@'),
REPLACE(name,'%20', ' '),
REPLACE(icon_clicked, 1, 'Yes'),
REPLACE(icon_clicked, 0, 'No')
FROM myTable
WHERE id > 1000;
But this query created an additional column for the 'No' string replace (so final result had 4 columns, email, name, icon_clicked->yes, icon_clicked->no)
Change multiple columns in a single MySQL query? For this, use UPDATE and REPLACE () in MySQL. Let us first create a table − mysql> create table DemoTable -> ( -> StudentId int NOT NULL AUTO_INCREMENT PRIMARY KEY, -> StudentName varchar (100), -> StudentCountryName varchar (100) -> ); Query OK, 0 rows affected (0.67 sec)
MySQL Find and Replace Values. Often times you want to search through an entire column in a MySQL table and do a find and replace on that column. MySQL has a wonderful string function called Replace(). This allows you to pass a field along with a value you wish to find in the field, and replace it with a value of your choice.
Using MySQL REPLACE to insert data from a SELECT statement The following illustrates the REPLACE statement that inserts data into a table with the data come from a query. REPLACE INTO table_1 (column_list) SELECT column_list FROM table_2 WHERE where_condition; Note that this form of the REPLACE statement is similar to INSERT INTO SELECT statement.
Insert the new row into the table again. To determine whether the new row that already exists in the table, MySQL uses PRIMARY KEY or UNIQUE KEY index. If the table does not have one of these indexes, the REPLACE works like an INSERT statement. To use the REPLACE statement, you need to have at least both INSERT and DELETE privileges for the table.
One way is to nest REPLACE
:
SELECT REPLACE(REPLACE(icon_clicked, 0, 'No'), 1, 'Yes')), ...
FROM myTable
...
or use CASE WHEN
(this will work for most RDBMS comparing to IF
function which is MySQL related):
SELECT CASE WHEN icon_clicked THEN 'Yes' ELSE 'No' END, ...
FROM myTable
...
SqlFiddleDemo
EDIT:
There is also one nice way utilizing ELT
:
SELECT icon_clicked,
ELT(FIELD(icon_clicked,0,1),'No','Yes'),
ELT(icon_clicked + 1, 'No', 'Yes')
FROM mytable
SqlFiddleDemo2
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With