MySQL CASE 语句

在 MySQL 中, CASE 语句相当于 if-elseif-else,用于流程控制中的多分支情况。

CASE 语法

这里是 MySQL CASE 语句的语法:

CASE value
    WHEN compare_value THEN result
    [WHEN compare_value THEN result ...]
    [ELSE result]
END

或者

CASE
    WHEN condition THEN result
    [WHEN condition THEN result ...]
    [ELSE result]
END

返回值

CASE 语句返回 condition 为真或者 value = compare_value 为真的 THEN 子句中指定的值。

CASE 示例

CASE 语句用于多个逻辑判断分支的情况。下面的例子展示了如何通过工作日索引(06)返回对应的工作日的名称。

首先,让我们创建一个表 test_case_weekday 用于演示。

DROP TABLE IF EXISTS test_case_weekday;
CREATE TABLE test_case_weekday (
    weekday_index INT NOT NULL
);

让我们插入几个数据:

INSERT INTO test_case_weekday
VALUES (0), (1), (2), (3), (4), (5), (6);

现在表中具有了如下数据:

+---------------+
| weekday_index |
+---------------+
|             0 |
|             1 |
|             2 |
|             3 |
|             4 |
|             5 |
|             6 |
+---------------+

如果我们想在查询中同时查出工作日索引对应的工作日的名称,可以使用 CASE 语句。如下:

SELECT
    weekday_index AS `Weekday Index`,
    CASE weekday_index
        WHEN 0 THEN 'Monday'
        WHEN 1 THEN 'Tuesday'
        WHEN 2 THEN 'Wednesday'
        WHEN 3 THEN 'Thursday'
        WHEN 4 THEN 'Friday'
        WHEN 5 THEN 'Saturday'
        WHEN 6 THEN 'Sunday'
        ELSE 'Error'
    END AS `Weekday Name`
FROM
    test_case_weekday;
+---------------+--------------+
| Weekday Index | Weekday Name |
+---------------+--------------+
|             0 | Monday       |
|             1 | Tuesday      |
|             2 | Wednesday    |
|             3 | Thursday     |
|             4 | Friday       |
|             5 | Saturday     |
|             6 | Sunday       |
+---------------+--------------+

这里我们也可以使用第二种语法来改写上面的语句:

SELECT
    weekday_index AS `Weekday Index`,
    CASE
        WHEN weekday_index = 0 THEN 'Monday'
        WHEN weekday_index = 1 THEN 'Tuesday'
        WHEN weekday_index = 2 THEN 'Wednesday'
        WHEN weekday_index = 3 THEN 'Thursday'
        WHEN weekday_index = 4 THEN 'Friday'
        WHEN weekday_index = 5 THEN 'Saturday'
        WHEN weekday_index = 6 THEN 'Sunday'
        ELSE 'Error'
    END AS `Weekday Name`
FROM
    test_case_weekday;

输出结果与上面完全相同。