在哪些情况下,MySQL CASE 语句会返回 NULL?


众所周知,如果没有比较或条件为真,则 CASE 语句将返回ELSE语句之后的result 。但是如果没有ELSE语句,则在这种情况下,CASE 语句将返回 NULL。下面是一个示例来说明这一点。

示例

mysql> Select CASE 100
    -> WHEN 150 THEN 'It is matched'
    -> WHEN 200 THEN 'It is not matched'
    -> END As 'It Returns NULL';
+-----------------+
| It Returns NULL |
+-----------------+
| NULL            |
+-----------------+
1 row in set (0.00 sec)

下面的查询使用表‘Students’中的数据,因为没有学生属于国家 WI 而返回 NULL。

mysql> Select SUM(CASE WHEN country = 'USA' THEN 1 ELSE 0 END) AS USA,
    -> SUM(CASE WHEN country = 'UK' THEN 1 ELSE 0 END) AS UK,
    -> SUM(CASE WHEN country = 'INDIA' THEN 1 ELSE 0 END) AS INDIA,
    -> SUM(CASE WHEN country = 'Russia' THEN 1 ELSE 0 END) AS Russia,
    -> SUM(CASE WHEN country = 'France' THEN 1 ELSE 0 END) AS France,
    -> SUM(CASE WHEN country = 'NZ' THEN 1 ELSE 0 END) AS NZ,
    -> SUM(CASE WHEN country = 'Australia' THEN 1 ELSE 0 END) AS Australia,
    -> SUM(CASE WHEN country = 'WI' THEN 1 END) AS WI
    -> From Students;
+------+------+-------+--------+--------+------+-----------+------+
| USA  | UK   | INDIA | Russia | France | NZ   | Australia | WI   |
+------+------+-------+--------+--------+------+-----------+------+
| 2    | 1    | 2     | 1      | 1      | 1    | 1         | NULL |
+------+------+-------+--------+--------+------+-----------+------+
1 row in set (0.00 sec)

更新于: 11-Feb-2020

1K+ 浏览

开启你的 职业生涯

通过完成课程获得认证

开始
广告