繁体   English   中英

MySql 如何 COUNT(column_name = 'foobar' or null) 工作?

[英]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'

是一个布尔表达式,它被评估为1true0false

因此,通过在此处将其与COUNT()一起使用:

count(columnB = 'foobar')

它等效于count(0)count(1) ,它们都返回相同的结果:

表中所有行的count(*)就像count(*)

因为COUNT()的参数永远不是NULL

表达方式:

columnB = 'foobar' or null

也是一个布尔表达式,但当columnB = 'foobar'falsefalse or nullnull ,而true or nulltrue )时,它也可能被评估为null

因此,通过在此处将其与COUNT()一起使用:

count(columnB = 'foobar' or null)

它只计算columnB = 'foobar'true ,因为对于所有其他columnB = 'foobar' or nullnull

尽管您的代码有效,但我更喜欢使用条件聚合,例如:

count(case when columnB = 'foobar' then 1 end)

要么:

sum(columnB = 'foobar') -- works in MySql and SQLite

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM