How Do I Count Users Per Group with MySQL?
-
28-10-2019 - |
Question
I have a table of groups:
- id -- a unique ID (primary key)
- group -- a group name
I have a table of users:
- username -- a unique string (primary key)
- group_id -- a foreign key link to group.id
In this case, a user is only going to be in one single group. So, in MySQL, how do I list out groups and their count of member users?
I tried using a subselect and count, but it ends up showing the same count on all groups.
Solution
SELECT group.id,COUNT(users.username) FROM groups
INNER JOIN users ON users.group_id=groups.id
GROUP BY groups.id
You can use a LEFT JOIN instead if you want to display empty groups per @Michael's comment
OTHER TIPS
select g.group, count(*) as group_count
from groups g, users g
where g.id=u.group_id
group by g.groupname
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow