renevdkooi
renevdkooi

Reputation: 1643

sql query to return 0 instead of NULL

I have the following statement, and it works fine, except for the fact that if, the 2nd table has no reference items to the first table it will return no results.

What I need is it to return count(p.match_id) AS matchcount as 0

"SELECT c.*, count(p.match_id) AS matchcount 
    FROM ci_address_book c LEFT JOIN ci_matched_sanctions p
    ON c.id = p.addressbook_id 
    GROUP BY p.addressbook_id ORDER BY c.id LIMIT ".$offset.",".$num;

Upvotes: 1

Views: 77

Answers (1)

Gates VP
Gates VP

Reputation: 45307

First problem here is that you're using a LEFT JOIN. This means that all rows in c will be returned even if they don't match the rows in p.

Your problem.

if the 2nd table has no reference items to the first table it will return no results

Let me rephrase this in my own words.

if the p table has no reference items to the c table it will not return any results

When you do a LEFT JOIN, anything in the "right" table that is empty will come back with values of NULL. So matchcount is going to be "NULL" in these cases. (you can tests this by doing select c.*, p.* ... where p.addressbook_id = NULL)

To display a "0" instead you do the following:

SELECT c.*, COALESCE(COUNT(p.match_id), 0) AS matchcount

COALESCE returns the first non-NULL value. So when COUNT(p.match_id) is NULL, you get 0.

Upvotes: 1

Related Questions