天天看點

MySQL CASE 函數

定義

CASE 函數允許在查詢時判斷設定判斷條件, 根據判斷條件,傳回第一個值為true的結果。

如果沒有條件符合,則執行ELSE語句的傳回值,如果沒有ELSE語句,則傳回NULL

文法

CASE expression
    WHEN condition1 THEN result1
    WHEN condition2 THEN result2
   ...
    WHEN conditionN THEN resultN
    ELSE result
END
           

參數值

參數 描述
expression 可選,值将會與when的條件比較
condition1, condition2, …conditionN 必須,按照列出的順序與值比較,當有一個條件滿足時,傳回結果,傳回的比較不再進行
result1, result2, …resultN 必須,當條件為true時傳回的結果

例子

SELECT OrderID, Quantity,
CASE
    WHEN Quantity >  THEN "The quantity is greater than 30"
    WHEN Quantity =  THEN "The quantity is 30"
    ELSE "The quantity is something else"
END
FROM OrderDetails;
           
SELECT CustomerName, City, Country
FROM Customers
ORDER BY
(CASE
    WHEN City IS NULL THEN Country
    ELSE City
END);
           

繼續閱讀