MySQL的count计数条件问题

xiaohai 2019-05-23 15:54:53 2844人围观 标签: Mysql 
简介某些时候我们需要通过在使用count的过程中,只需要计算某些条件下的记录数,这时候我们就需要使用到Count条件计数问题。

数据如下表:如果需要统计等级分别为1,2,3的总人数,那么我们如何实现呢?

id name level
1 张三 1
2 李四 2
3 王五 3
4 张二娃子 1
5 李旦 1
6 狗娃子 2
1、方式一
mysql> select count(level = 1 or null) as '等级1',count(level = 2 or null) as '等级2',count(level = 3 or null) as '等级3' from users; +-------+-------+-------+ | 等级1 | 等级2 | 等级3 | +-------+-------+-------+ | 3 | 2 | 1 | +-------+-------+-------+ 1 row in set (0.05 sec)

上面的SQL一定要注意,必须加上or null,为什么呢?

count统计的是不为null的数;但是false不为null,所以会被统计上;
如果要让表达式为null,所以就需要or null表达式,false or null后就是null,所以就不会被统计上

2、方式二
mysql> select count(case when level=1 then level end) as '等级1',count(case when level=2 then level end) as '等级2',count(case when level=3 then level end) as '等级3' from users; +-------+-------+-------+ | 等级1 | 等级2 | 等级3 | +-------+-------+-------+ | 3 | 2 | 1 | +-------+-------+-------+ 1 row in set (0.04 sec)