I am trying to pull out the information about each user group, while counting the number of users in each.
The counting works, however if a group does not contain any users, it does not retrieve the information – it simply gets ignored.
This is my query:
SELECT
g.*,
count(u.username) as total,
u.usergroup
FROM
usergroups as g,
users as u
WHERE
u.usergroup = g.g_id
GROUP BY
g.group_name
This is a part of my “users” and “user groups” tables:
Sample usergroups table structure
+--------------------------+---------------+
| Field | Type |
+--------------------------+---------------+
| g_id | int(10) |<- the user group's ID.
| group_name | varchar(255) |<- the name of the user group
+--------------------------+---------------+
Sample users table structure
+--------------------------+---------------+
| Field | Type |
+--------------------------+---------------+
| id | int(10) |<- the user ID
| username | varchar(255) |<- the username
| usergroup | int(10) |<- ID of the user group the user is in
+--------------------------+---------------+
I have no idea what I have missed – but then again, I am very new to more complex queries (if you can call it that).
Any help would be very appreciated!
You want a
left join, and you’re doing aninner join:Now that I have your attention, I’d like to take a minute to discuss what join conditions are. See, when you’re first learning MySQL, they teach you the syntax you use. And hey, it works great, for certain sets of problems. Unfortunately, it causes you to equate “join condition” with “where predicate,” and that’s a problem.
In this case, we’re saying, “Hey, MySQL, grab me all the stuff out of the
usergroupstable, and try to find a match to theuserstable where theu_idcolumn fromusergroupsequals theusergroupcolumn fromusers. If you can’t find anything, that’s okay, bring theusergroupback anyway, and just null out the columns thatusersbrings to the table.”Previously, you were saying, “Hey, MySQL, grab me all the stuff out of the
usergroupsand theuserstable, but only where theu_idcolumn fromusergroupsmatches theusergroupcolumn fromusers.”If you had done it with
inner joinsyntax, like so:You would have been saying, “Hey, MySQL, grab me everything from the
usergroupstable, and then go find everything in theuserstable whereu_idequalsusergroup. If you don’t find a match, I don’t want to see that usergroup show up in the results.So, to be clear, the where predicates filter the result set, whereas the join conditions map one table to another.