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)

原文地址:https://www.cnblogs.com/zhangww/p/9997607.html