如何让 MySQL 中的 SUM 函数返回“0”?如果没有找到值?
假设我在 MySQL 中有一个简单的函数:
SELECT SUM(Column_1)
FROM Table
WHERE Column_2 = 'Test'
如果 Column_
2 中没有条目包含文本“Test”,则该函数返回 NULL
,而我希望它返回 0。
我知道类似的问题已经在这里被问过几次,但我无法根据我的目的调整答案,所以我将不胜感激您提供一些帮助来解决这个问题。
Say I have a simple function in MySQL:
SELECT SUM(Column_1)
FROM Table
WHERE Column_2 = 'Test'
If no entries in Column_
2 contain the text 'Test' then this function returns NULL
, while I would like it to return 0.
I'm aware that a similar question has been asked a few times here, but I haven't been able to adapt the answers to my purposes, so I'd be grateful for some help to get this sorted.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
使用
COALESCE
以避免这种结果。要查看它的实际效果,请参阅此 sql fiddle: http://www.sqlfiddle .com/#!2/d1542/3/0
更多信息:
给定三个表(一张包含所有数字,一张包含所有空值,一张包含混合):
SQL Fiddle
MySQL 5.5.32 架构设置:
查询 1 :
结果:
Use
COALESCE
to avoid that outcome.To see it in action, please see this sql fiddle: http://www.sqlfiddle.com/#!2/d1542/3/0
More Information:
Given three tables (one with all numbers, one with all nulls, and one with a mixture):
SQL Fiddle
MySQL 5.5.32 Schema Setup:
Query 1:
Results:
使用
IFNULL
或COALESCE
:它们之间的区别在于<代码>IFNULL是一种采用两个参数的 MySQL 扩展,而
COALESCE
是一种可以采用一个或多个参数的标准 SQL 函数。当只有两个参数时,使用 IFNULL 会稍微快一些,但这里的差异微不足道,因为它只被调用一次。Use
IFNULL
orCOALESCE
:The difference between them is that
IFNULL
is a MySQL extension that takes two arguments, andCOALESCE
is a standard SQL function that can take one or more arguments. When you only have two arguments usingIFNULL
is slightly faster, though here the difference is insignificant since it is only called once.无法准确得到您所要求的内容,但如果您使用的是聚合 SUM 函数,则意味着您正在对表进行分组。
MYSQL 的查询是这样的
Can't get exactly what you are asking but if you are using an aggregate SUM function which implies that you are grouping the table.
The query goes for MYSQL like this
如果列的总和为 0 则显示为空
if sum of column is 0 then display empty