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