如何替换select中列中的所有非零值



我需要替换select语句中列中的非零。

SELECT Status, Name, Car from Events;

我可以这样做:

SELECT (Replace(Status, '1', 'Ready'), Name, Car from Events;

或者使用案例/更新。

但我有-5到10的数字,为每种情况写替换或其他东西不是个好主意。

如何在不更新数据库的情况下添加comparasing和replace?

表格如下:

Status     Name    Car 
0          John    Porsche
1          Bill    Dodge
5          Megan   Ford

标准方法是使用case:

select t.*,
(case when status = 1 then 'Ready'
else 'Something else'
end) as status_string
from t;

不过,我建议你有一个状态参考表:

create table statuses (
status int primary key,
name varchar(255)
);
insert into statuses (status, name)
values (0, 'UNKNOWN'),
(1, 'READY'),
. . .  -- for the rest of the statuses

然后使用JOIN:

select t.*, s.name
from t join
statuses s
on t.status = s.status;
SELECT IF(status =1, 'Approved', 'Pending') FROM TABLENAME

最新更新