簡體   English   中英

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

[英]How to replace all non-zero values from column in select?

我需要替換 select 語句中列中的非零值。

SELECT Status, Name, Car from Events;

我可以這樣做:

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

或使用案例/更新。

但是我有從 -5 到 10 的數字,並且為每種情況編寫 Replace 或其他東西並不是一個好主意。

如何在不更新數據庫的情況下添加比較與替換?

表如下所示:

Status     Name    Car 
0          John    Porsche
1          Bill    Dodge
5          Megan   Ford
SELECT IF(status =1, 'Approved', 'Pending') FROM TABLENAME

標准方法是用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;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM