Jump to content

result of sum() on some records = null I need it to be 0


kevinkorb

Recommended Posts

Here is my query::

SELECT sum( bcf.score ) AS score, pu.username,  bc.timestamp, bc.timestamp, bc.comment, bc.id
FROM blog_comments AS bc
LEFT JOIN blog_comments_feedback AS bcf ON bc.id = bcf.comment_id
JOIN peatot_users AS pu ON pu.id = bc.commenter_id
GROUP BY bc.id

ORDER BY score DESC
LIMIT 0 , 30"

The score can be negative or positive.  However when there are no associated records in bcf, score is null which throws that after all the negatives.

Any ideas.

Thanks.
Link to comment
Share on other sites

seeing your doing a LEFT JOIN and you might get a null, just wrap SUM( bcf.score ) with...

[code]COALESCE(SUM(bcf.score))[/code]

But by default both SUM() and COUNT() should ignore NULL, so you shouldn't have to test for them or do anything special, but that depends on your MySQL version. If that doesn't work, you can always use IF(), but you shouldn't have to...

[code]SUM(IF(bcf.score IS NULL,0,bcf.score))[/code]

printf
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.