[英]MySql how COUNT(column_name = 'foobar' or null) works?
我想了解or null
在这个例子中是如何工作的:
Select columnA, count(columnB = 'foobar' or null) as result
from orders
group by columnA
如果我不使用or null
那么它只给出基于 group by 的 columnB 的计数(*)但是使用or null
它给出正确的值计数,其中columnB = 'foobar'
只是想知道它在内部是如何工作的?
假设columnB
不可为空,则表达式:
columnB = 'foobar'
是一个布尔表达式,它被评估为1
为true
或0
为false
。
因此,通过在此处将其与COUNT()
一起使用:
count(columnB = 'foobar')
它等效于count(0)
或count(1)
,它们都返回相同的结果:
表中所有行的
count(*)
就像count(*)
)
因为COUNT()
的参数永远不是NULL
。
表达方式:
columnB = 'foobar' or null
也是一个布尔表达式,但当columnB = 'foobar'
为false
( false or null
为null
,而true or null
为true
)时,它也可能被评估为null
。
因此,通过在此处将其与COUNT()
一起使用:
count(columnB = 'foobar' or null)
它只计算columnB = 'foobar'
为true
,因为对于所有其他columnB = 'foobar' or null
为null
。
尽管您的代码有效,但我更喜欢使用条件聚合,例如:
count(case when columnB = 'foobar' then 1 end)
要么:
sum(columnB = 'foobar') -- works in MySql and SQLite
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.