1. 程式人生 > >mysql聚合函式count(1) sum(1)結果返回0和NULL

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)