解决mysql的count()函数条件表达式不生效的问题

示例

表数据
在这里插入图片描述

统计错误的sql

select count(age = 10) as count from student

查询结果
在这里插入图片描述

原因

count(‘任意内容’)都会统计出所有记录数,因为count只有在遇见null时才不计数,即count(null)==0

解决

方法1:count()函数中条件表达式加上or null

select count(age = 10 or null) as count from student

方法2:使用IF()函数,当不满足条件时表达式的值为NULL

select count(IF(age = 10,1,null)) as count from student

方法3:使用case when表达式,当不满足条件时表达式的值为NULL

select count(case when age = 10 then 1 else null end) as count from student

猜你喜欢

转载自blog.csdn.net/weixin_52116015/article/details/131638350
今日推荐