Click to See Complete Forum and Search --> : Returning zero for a query sum


NotionCommotion
04-10-2006, 01:59 AM
I would like to perform a query sum of a table, and return 0 (i.e. zero) and not NULL if there is no matching data. The query that returns NULL (providing nothing matches) is:
SELECT SUM(my_column) AS temp_name FROM my_table WHERE id=1;

Don’t think if it matters, but I am using PHP to interface to MySQL, and am using the following code:
$sql="SELECT SUM(my_column) AS temp_name FROM my_table WHERE id=1";
$rs=mysql_query($sql, $conn);
$results=mysql_fetch_array($rs);
$total_my_column=$results[temp_name];

Any suggestions would be very appreciated.

Thank you very much!

john_de116
04-10-2006, 02:26 AM
SELECT SUM(my_column) AS temp_name FROM my_table WHERE id=1 group by my_column.

Use it. Surely it satisfies your requirements

NogDog
04-10-2006, 02:28 AM
Could you just add this to the PHP?

if(!$total_my_column)
{
$total_my_column = 0;
}

NotionCommotion
04-10-2006, 11:37 AM
Thanks john_de116, I will give it a try.

NogDog, I didn't really convey everything I am doing, and am actually using the sum in another equation. I would like to have SQL do all the calculations, and not have it do part, then turn it over to PHP, and then back to SQL.

NotionCommotion
04-11-2006, 01:59 AM
john_de116, I tried your suggestion, but get an "empty set" and not a zero. For instance, with the following, I would expect temp_name to equal 10 if there are no matches, but instead get nothing.

SELECT (10+SUM(my_column)) AS temp_name FROM my_table WHERE id=1 group by my_column.

I suppose I can add a row with all zero's, but that sounds like a weak fix that might cause problems down the road.

Any suggestions? Thanks for your help.