How do I get SUM function in MySQL to return '0' if no values are found?

前端 未结 4 656
萌比男神i
萌比男神i 2020-11-29 18:07

Say I have a simple function in MySQL:

SELECT SUM(Column_1)
FROM Table
WHERE Column_2 = \'Test\'

If no entries in Column_2 con

4条回答
  •  孤独总比滥情好
    2020-11-29 18:10

    Use IFNULL or COALESCE:

    SELECT IFNULL(SUM(Column1), 0) AS total FROM...
    
    SELECT COALESCE(SUM(Column1), 0) AS total FROM...
    

    The difference between them is that IFNULL is a MySQL extension that takes two arguments, and COALESCE is a standard SQL function that can take one or more arguments. When you only have two arguments using IFNULL is slightly faster, though here the difference is insignificant since it is only called once.

提交回复
热议问题