MYSQL 控制流函数 CASE 如何工作?

mysqlmysqli database更新于 2023/11/16 19:00:00

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)

Syntax-2

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

在此第二种语法中,如果条件为真,则 CASE 语句返回 result1、result2 等。如果所有条件均为假,则 CASE 语句返回在 ELSE子句中指定的结果

示例

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)

相关文章