扩展SELECT IF语句

时间:2017-07-05 03:09:30

标签: mysql

我正在使用SELECT IF语句来翻译我的数据库中的数据:

IF(status = 1, 'Status one', 'Status two')

如果状态为1,则语句显示Status one。如果状态是其他内容,则语句显示Status two

我想扩展此声明并显示:

IF status = 1, 'Status one'
IF status = 2, 'Status two'
IF status = 3, 'Status three'
IF status = 4, 'Status four'

有人知道我该怎么做吗?

2 个答案:

答案 0 :(得分:3)

这样的事情应该有效:

SELECT
    (CASE 
        WHEN status = 1 THEN 'Status one'
        WHEN status = 2 THEN 'Status two'
        WHEN status = 3 THEN 'Status three'
        WHEN status = 4 THEN 'Status four'
        ELSE 'Incorrect Option'
    END) AS statustext
FROM yourtable;

根据ysth的评论,这是更紧凑,可能更有效:

SELECT
    (CASE status
        WHEN 1 THEN 'Status one'
        WHEN 2 THEN 'Status two'
        WHEN 3 THEN 'Status three'
        WHEN 4 THEN 'Status four'
        ELSE 'Incorrect Option'
    END) AS statustext
FROM yourtable;

谢谢你!

答案 1 :(得分:2)

您还可以使用CASE表达式:

SELECT
    CONCAT('Status ',
        CASE WHEN status = 1 THEN 'one'
             WHEN status = 2 THEN 'two'
             WHEN status = 3 THEN 'three'
             WHEN status = 4 THEN 'four' END) AS label
FROM yourTable

Demo