I have two tables groups and users. I want to write a query that returns the rows from groups with an extra column that says how many rows in users have a gid that matches the id of the corresponding group. I have written a query that works fine, except in the case where there are no users in the users table with a corresponding gid, in which case that group is omitted from the result.
SELECT a.id, a.admin, a.name, COUNT(b.zbid) users FROM groups a LEFT JOIN users b ON b.gid=a.id
How can I get around this? I have worked out that it is definitely the COUNT that breaks the functionality. Why? Well if I try the following:
SELECT a.id, a.admin, a.name, IF(ISNULL(b.zbid), 0, 1) users FROM groups a LEFT JOIN users b ON b.gid=a.id WHERE a.cid='1'
then no rows are omitted, and it will show users=1 for any row with corresponding users, and 0 otherwise. However, if I change this to:
SELECT a.id, a.admin, a.name, IF(ISNULL(b.zbid), 0, COUNT(b.zbid)) users FROM groups a LEFT JOIN users b ON b.gid=a.id WHERE a.cid='1'
then it omits the rows again...
Any help would be appreciated.