MySQL 控制流函式 CASE 如何工作?


MySQL CASE 語句是一個流控制函式,允許我們在 SELECT 或 WHERE 子句之類的查詢中構建條件。CASE 語句有兩種語法

語法 1

CASE val
WHEN compare_val1 THEN result1
WHEN compare_val2 THEN result2
.
.
.
Else result
END

在此第一個語法中,如果 val 等於 compare_val1,則 CASE 語句返回 result1。如果 val 等於 compare_val2,則 CASE 語句返回 result2,依此類推。

如果 val 與任何 compare_val 不匹配,則 CASE 語句將返回 ELSE 子句中指定的 result

示例

mysql> Select CASE 100
    -> WHEN 100 THEN 'It is matched'
    -> WHEN 200 THEN 'It is not matched'
    -> ELSE 'No use of this Number'
    -> END as 'Matching the Number';
+---------------------+
| Matching the Number |
+---------------------+
| It is matched       |
+---------------------+
1 row in set (0.06 sec)

語法 2

CASE
WHEN condition_1 THEN result1
WHEN condition_2 THEN result2
.
.
.
Else result
END

在此第二個語法中,如果條件為真,則 CASE 語句將返回result1、result2 等。如果所有條件均為假,則 CASE 語句將返回 ELSE 子句中指定的 result

示例

mysql> Select CASE
    -> WHEN (100 = 100) THEN 'It is Matched'
    -> WHEN (200 = 100) Then 'It is Not Matched'
    -> Else 'No use of Number'
    -> END as 'Matching the Number';
+---------------------+
| Matching the Number |
+---------------------+
| It is Matched       |
+---------------------+
1 row in set (0.00 sec)

更新於: 2020-02-11

289 次瀏覽

開啟 職業生涯

透過完成課程獲得認證

開始
廣告