I’m trying to return a simple list of all items in table A (groups) with a count of the corresponding number of users in column B (users_groups) and I can’t figure out where I’m going wrong.
SELECT groups.gid, name, COUNT(uid) AS groupcount
FROM groups
LEFT OUTER JOIN users_groups ON groups.gid = users_groups.gid
WHERE aid = ?
I currently have two groups, one of which has three users. That row returns with the proper value in groupcount but I’m missing what should be the second row displayed with a 0 groupcount. Can anyone point me in the right direction? Thanks!
Presumably this is because aid is in users_groups and not in groups.
The left outer join will create a row where this is NULL. Any comparison other than “is null” will result in no match.
You can fix this by doing something like:
If that is the intention of your query.
Or, another alternative, is that you don’t have a group by in your query. Try this:
Mysql has the disfeature that you can include unaggregated columns in the SELECT clause. However, it only groups by what is in the group by. Since you have nothing specified for grouping, it is producing one row over all the data. The values of gid and name are arbitrarily chosen from the input.