首页  >  文章  >  数据库  >  MySQL CASE语句在什么情况下返回NULL?

MySQL CASE语句在什么情况下返回NULL?

王林
王林转载
2023-08-25 13:45:121546浏览

MySQL CASE语句在什么情况下返回NULL?

我们知道,如果没有比较或条件为 true,则 CASE 语句将返回 ELSE 语句之后指定的结果。但是,如果没有 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”中的数据,返回 NULL,因为没有学生属于 WI 国家/地区。

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)

以上是MySQL CASE语句在什么情况下返回NULL?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文转载于:tutorialspoint.com。如有侵权,请联系admin@php.cn删除