简体   繁体   English

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

[英]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 .是一个布尔表达式,它被评估为1true0false

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'falsefalse or nullnull ,而true or nulltrue )时,它也可能被评估为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 nullnull

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.

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