MySQL 控制流程函数 CASE 如何工作?
MySQL CASE 语句是流程控制函数,允许我们在查询中建立条件,例如 SELECT 或 WHERE 子句。我们有两种语法形式的 CASE 语句。
阅读更多:MySQL 教程
语法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, etc. 。如果所有的条件都是 false,则 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)