MYSQL 控制流函式 CASE 是如何執行的?
MySQL CASE 語句是一種流控制函式,它允許我們在查詢中(如 SELECT 或 WHERE 子句)構建條件。我們有兩種 CASE 語句的語法
語法 1
CASE val WHEN compare_val1 THEN result1 WHEN compare_val2 THEN result2 . . . Else result END
在此 1 個語法中,如果 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
在此 2 個語法中,如果條件為真,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)
廣告