Mysql使用sum()函数返回null的问题详解

目录
  • 介绍
  • 问题
  • 验证
  • 解决
  • 区别
  • 参考
  • 总结

介绍

sum()函数用于计算一组值或表达式的总和,sum()函数的语法如下:

sum(distinct expression)

sum()函数是如何工作的?

  • 如果在没有返回匹配行select语句中使用sum函数,则sum函数返回null,而不是0。
  • distinct运算符允许计算集合中的不同值。
  • sum函数忽略计算中的null值。

问题

在项目中使用 mysql 中的 sum() 函数求和时,调试时发现报出下面的错误信息:

sql: scan error on column index 0, name “total”: converting null to int64 is unsupported

我相应执行的sql语句如下:

select sum(consume) as total from task_income where consume_type=3 and uid=20;

验证

为了找到原因,我在 navicat 中执行了一遍出问题的sql和参数,发现结果中确实是返回了 null :

按我之前开发时的想法:

  • 如果有相应的数据,返回求和后的值
  • 如果没有符合条件的数据,返回 0

结果,当没有符合条件的数据时却返回了 null 。

解决

可以通过结合使用 isnull 或 coalesce 函数来解决。

相应的示例如下:

select ifnull(sum(column1), 0) as total from...

select coalesce(sum(column1), 0) as total from...

区别

上面说道,使用 isnull 或 coalesce 函数都可以解决为 null 的问题,那么这两个函数有什么区别呢?

  • isnull 函数接受两个参数,如果第一个参数不是 null 会直接返回,如果第一个参数是 null ,则返回第二个参数
  • coalesce 函数可以接受两个或多个参数,并返回第一个非 null 的参数,如果所有参数都为 null,则会返回 null

参考

  • how do i get sum function in mysql to return ‘0’ if no values are found? – stack overflow
  • sql – what is the difference bewteen ifnull and coalesce in mysql? – stack overflow

总结

到此这篇关于mysql使用sum()函数返回null问题的文章就介绍到这了,更多相关mysql用sum()返回null内容请搜索www.887551.com以前的文章或继续浏览下面的相关文章希望大家以后多多支持www.887551.com!

(0)
上一篇 2022年3月21日
下一篇 2022年3月21日

相关推荐