How to replace multiple values โ€‹โ€‹in 1 column in mysql SELECT query with REPLACE ()?

I have a table with boolean values โ€‹โ€‹(only 0 and 1) that should be CSV-ed for the client. I know that I can do 1 replace as follows:

SELECT REPLACE(email, '%40', '@'), REPLACE(name,'%20', ' '), REPLACE(icon_clicked, 1, 'Yes') FROM myTable WHERE id > 1000; 

This converts all the values โ€‹โ€‹of 1 to "Yes", but how to do it in one query for 1 => Yes and 0 => No, so the logical result is stored in one 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 to replace the row โ€œNoโ€ (so the final result consisted of 4 columns, email, name, icon_clicked-> yes, icon_clicked-> no)

+5
source share
2 answers

One way is to REPLACE :

 SELECT REPLACE(REPLACE(icon_clicked, 0, 'No'), 1, 'Yes')), ... FROM myTable ... 

or use CASE WHEN (this will work for most RDBMSs compared to the IF function, which is related to MySQL):

 SELECT CASE WHEN icon_clicked THEN 'Yes' ELSE 'No' END, ... FROM myTable ... 

SqlFiddleDemo

EDIT:

There is also one good way to use ELT :

 SELECT icon_clicked, ELT(FIELD(icon_clicked,0,1),'No','Yes'), ELT(icon_clicked + 1, 'No', 'Yes') FROM mytable 

SqlFiddleDemo2

+6
source

No need to use a nested Replace or Case statement. Try using IF , which is a lot easier.

 SELECT icon_clicked, IF(icon_clicked,'Yes','No') FROM myTable 
+3
source

Source: https://habr.com/ru/post/1239365/


All Articles