문제

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.

도움이 되었습니까?

해결책

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

다른 팁

select g.group, count(*) as group_count
from groups g, users g
where g.id=u.group_id
group by g.groupname
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top