How to select sum -or- 0 if no records exist?

前端 未结 4 967
闹比i
闹比i 2020-12-09 14:48

I need to write a query that returns the sum of all values that meet a certain criteria, but the query needs to return 0 if no rows are found, rather than null. For example

4条回答
  •  忘掉有多难
    2020-12-09 15:25

    Check the MySQL documentation for IFNULL.

    SELECT SUM(IFNULL(num, 0)) as val FROM tab WHERE descr LIKE "%greetings%";
    

    Of course, this assumes your num field is nullable and doesn't have a default value. Another possible solution would be to set a default of 0 for the num field which should solve the issue you're having.

提交回复
热议问题