mysql中count带条件查询——count( 条件 or null )(好文章!)
方法一:SELECTcount(t.command_name = 'UNLOCK'OR NULL) unlockFrequencyFROM表 t1234567方法二:select count(t.command_name) from t where t.command_name = 'UNLOCK'1方法三:select count(if( t.command_name = 'UNLOCK' ,1
四种方法:
方法一(推荐)
select
count(t.command_name = 'UNLOCK' OR NULL) as unlockFrequency
from
表 t
方法二
select
count(if(t.command_name = 'UNLOCK', 1, null))
from
表 t
方法三
select
sum(if(t.command_name = 'UNLOCK', 1, 0))
from
表 t
方法四
select count(t.command_name) from t where t.command_name = 'UNLOCK'
补充:
sql 语句中count()有条件的时候为什么要加上or null?
例如:
count(release_year = '2006' or NULL)
为什么要加上or NULL 直接count(release_year='2006')有什么问题吗?不就是要找release_year = '2006'的数据吗,为什么要计算NULL的数据
答案:
因为 当 release_year不是 2006时 ,release_year='2006' 结果false 不是 NULL,
Count在值是NULL时不统计数:
count('任意内容')都会统计出所有记录数,因为count只有在遇见null时不计数,即count(null)==0,因此前者单引号内不管输入什么值都会统计出所有记录数)
至于加上or NULL, 很像其他编程里的or运算符,第一个表达式是true就是不执行or后面的表达式,第一个表达式是false 执行or后面的表达式 。
当release_year不为2006时release_year = '2006' or NULL 的结果是NULL,Count才不会统计上这条记录数
————————————————
原文链接:
https://blog.csdn.net/qq_39629277/article/details/90754444
https://blog.csdn.net/qq_32719287/article/details/79513164
更多推荐
所有评论(0)