MySQL returns NULL when it places SUM with no records

0

I have the code SQL

  

SELECT sum (r.quantidade_domingo) AS quantity_domingo FROM reports   AS r INNER JOIN nodes AS n ON r.id_nucleo = n.id INNER JOIN users   AS u ON n.id_user = u.id WHERE u.id_regiao = '1' AND   MONTH (r.dia_domingo) = '11'

The problem is that in the reports table there is no record and in the phpmyadmin when I run the command, it returns me quantity_domain as NULL . When I hit Sum (amount_domain_domain) AS_quantity and replaced with r. * it returns me "No Registry" that would be right because in PHP it returns as if it had a line and I do not want it.

    
asked by anonymous 30.11.2015 / 22:30

1 answer

3

This is the default behavior of the SUM function, if it does not have records it returns NULL or if it has no value as well.

You can use COALESCE + SUM to solve this problem:

SELECT COALESCE(SUM(QUANTIDADE), 0) FROM RELATORIO;

Example: SQL Fiddle

    
30.11.2015 / 22:42