如何解决MySql 如何 COUNT(column_name = 'foobar' or null) 工作?
我想了解 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()
的参数永远不会是 NULL
。
表达式:
columnB = 'foobar' or null
也是一个布尔表达式,但当 null
为 columnB = 'foobar'
时,它也可以计算为 false
(false or null
为 null
,而 {{1 }} 是 true or null
)。
因此通过在此处与 true
一起使用:
COUNT()
它只计算 count(columnB = 'foobar' or null)
为 columnB = 'foobar'
的行,因为对于所有其他行,true
为 columnB = 'foobar' or null
。
尽管您的代码有效,但我更喜欢使用条件聚合,例如:
null
或:
count(case when columnB = 'foobar' then 1 end)
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。