[英]MySql how COUNT(column_name = 'foobar' or null) works?
I want to understand how or null
works in this example:我想了解
or null
在这个例子中是如何工作的:
Select columnA, count(columnB = 'foobar' or null) as result
from orders
group by columnA
If I don't use or null
then it just give the count(*) of columnB based on group by but with or null
it gives correct count of values where columnB = 'foobar'
如果我不使用
or null
那么它只给出基于 group by 的 columnB 的计数(*)但是使用or null
它给出正确的值计数,其中columnB = 'foobar'
Just wondering how it works internally?只是想知道它在内部是如何工作的?
Assuming that columnB
is not nullable, the expression:假设
columnB
不可为空,则表达式:
columnB = 'foobar'
is a boolean expression that is evaluated as 1
for true
or 0
for false
.是一个布尔表达式,它被评估为
1
为true
或0
为false
。
So by using it with COUNT()
here:因此,通过在此处将其与
COUNT()
一起使用:
count(columnB = 'foobar')
it is equivalent to count(0)
or count(1)
which both return the same result:它等效于
count(0)
或count(1)
,它们都返回相同的结果:
the number of all of the rows of the table (just like
count(*)
)表中所有行的
count(*)
就像count(*)
)
because the argument of COUNT()
is never NULL
.因为
COUNT()
的参数永远不是NULL
。
The expression:表达方式:
columnB = 'foobar' or null
is also a boolean expression, but it may also be evaluated as null
when columnB = 'foobar'
is false
( false or null
is null
, while true or null
is true
).也是一个布尔表达式,但当
columnB = 'foobar'
为false
( false or null
为null
,而true or null
为true
)时,它也可能被评估为null
。
So by using it with COUNT()
here:因此,通过在此处将其与
COUNT()
一起使用:
count(columnB = 'foobar' or null)
it counts only the rows where columnB = 'foobar'
is true
, because for all the others columnB = 'foobar' or null
is null
.它只计算
columnB = 'foobar'
为true
,因为对于所有其他columnB = 'foobar' or null
为null
。
Although your code works, I prefer to use conditional aggregation, like:尽管您的代码有效,但我更喜欢使用条件聚合,例如:
count(case when columnB = 'foobar' then 1 end)
or:要么:
sum(columnB = 'foobar') -- works in MySql and SQLite
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.