MySQL count problem
Posted
by Skuja
on Stack Overflow
See other posts from Stack Overflow
or by Skuja
Published on 2010-03-28T14:24:56Z
Indexed on
2010/03/28
14:33 UTC
Read the original article
Hit count: 226
I have 3 tables users(id,name),groups(id,name) and users_groups(user_id,group_id). users and groups have many to many relationship, so the third one is for storing users and groups relations. I would like to select all the data from groups with user count in each group. So far I came up with this:
SELECT groups.*, COUNT(users_groups.user_id) AS user_count
FROM groups
LEFT JOIN users_groups ON users_groups.group_id = groups.id
The problem is that query result is not returning any of groups which has no users (users_groups doesnt have any records with group_id of those groups).
How should I create my query to select all the groups and they user count, or user count as 0 if there are no users for that group?
© Stack Overflow or respective owner