2017-07-05 92 views
0

我使用SELECT IF語句將數據從我的數據庫翻譯:如果狀態爲1的語句顯示Status one擴展SELECT IF語句

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

。如果狀態是別的,則說明顯示Status two

我想延長這一說法,並顯示:

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

是否有人知道我該怎麼做呢?

+0

https://dev.mysql.com/doc/refman/5.7/en/control-flow-functions.html#operator_case – Alex

回答

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

+0

它工作。謝謝 – John

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

是的,它工作。謝謝 – John

+2

當你比較同一個表達式時,你可以改爲'case'當'1'然後'one'時2然後'two'當3然後'three'當4然後'4'else'nope'結束' – ysth