我们知道,如果没有比较或条件为真,则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)