Mysql聚合函数count(1) sum(1)结果返回0和NULL


1.count(1)

  • 返回为0
    如果所查询的表或者where条件筛选后得到的结果集为空,则 count(1)返回为 0
    如:
    select count(id) from test;
    select count(id) from test where id < 0;

  • 返回为NULL
    如果所查询的表或者where条件筛选后得到的结果集为空且当前层查询中使用了group by ,则 count(1)返回为 NULL
    如:
    select count(id) from test group by id;
    select count(id) from test where id < 0 group by id;

2.sum(1)

  • 返回为NULL
    如果所查询的表或者where条件筛选后得到的结果集为空 ,则 sum(1)返回为 NULL
    如:
    select sum(id) from test;
    select sum(id) from test where id < 0;

注:如果想NULL转为0返回可以使用IFNULL(expression_1,expression_2);表示如果expression_1不为NULL,则IFNULL函数返回expression_1; 否则返回expression_2的结果。
如IFNULL(sum(id),0)


免责声明!

本站转载的文章为个人学习借鉴使用,本站对版权不负任何法律责任。如果侵犯了您的隐私权益,请联系本站邮箱yoyou2525@163.com删除。



 
粤ICP备18138465号  © 2018-2025 CODEPRJ.COM