[英]How to replace multiple values in 1 column in mysql SELECT query using REPLACE()?
I have a table with Boolean values (0 and 1 only) that needs to be CSV-ed to a client. 我有一个表格,其中包含布尔值(仅限0和1),需要对客户端进行CSV格式化。 I know I can do 1 replace like this:
我知道我可以做1替换像这样:
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? 这会将1的所有值转换为'是',但如何在单个查询中为1 =>是和0 =>否这样做布尔结果存储在一个列中? 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) 但是这个查询为'No'字符串替换创建了一个额外的列(所以最终结果有4列,email,name,icon_clicked-> yes,icon_clicked-> no)
One way is to nest REPLACE
: 一种方法是嵌套
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): 或使用
CASE WHEN
(这与大多数RDBMS相比,与MySQL相关的IF
函数相比):
SELECT CASE WHEN icon_clicked THEN 'Yes' ELSE 'No' END, ...
FROM myTable
...
EDIT: 编辑:
There is also one nice way utilizing ELT
: 使用
ELT
还有一个很好的方法:
SELECT icon_clicked,
ELT(FIELD(icon_clicked,0,1),'No','Yes'),
ELT(icon_clicked + 1, 'No', 'Yes')
FROM mytable
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.