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;
First problem here is that you’re using a
LEFT JOIN. This means that all rows incwill be returned even if they don’t match the rows inp.Your problem.
Let me rephrase this in my own words.
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 matchcountCOALESCEreturns the first non-NULL value. So when COUNT(p.match_id) is NULL, you get 0.