简体   繁体   English

如何使用REPLACE()替换mysql SELECT查询中的1列中的多个值?

[英]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
...

SqlFiddleDemo

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

SqlFiddleDemo2

No need to use nested Replace or Case statement. 无需使用嵌套的ReplaceCase语句。 Try using IF , which is way simpler 尝试使用IF ,这更简单

SELECT 
   icon_clicked,
   IF(icon_clicked,'Yes','No')
FROM myTable

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM