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 那么它只是根据分组依据给出 columnB 的计数(*)但是使用 or null 它给出正确的值计数 columnB = 'foobar'

只是想知道它在内部是如何工作的?

假设 columnB 不可为空,则表达式:

columnB = 'foobar'

是一个布尔表达式,对于 true 被计算为 1 或对于 false 被计算为 0

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

count(columnB = 'foobar')

它等同于count(0)count(1)两者return相同的结果:

the number of all of the rows of the table (just like count(*))

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

表达式:

columnB = 'foobar' or null

也是一个布尔表达式,但当columnB = 'foobar'false时,它也可能被计算为nullfalse or nullnull,而true or nulltrue).

因此,在此处将其与 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