如何从每个组中获取成员数以及组详细信息?

时间:2015-02-02 10:15:11

标签: mysql database

我有以下MySQL表

users      :- user_id (PK)
groups     :- group_id (PK)
user_group :- user_group_id (PK),user_id(F Key),group_id(F Key)

我想知道用户加入的群组数以及每个群组的成员数。例如

user1 :- group1,group2
user2 :- group2,group3
user3 :- group1,group3

现在我想要这样的结果

user1:1(user_id)  group1:1(group_id) 2(member count)
user1:1(user_id)  group2:2(group_id) 2(member count)
user2:2(user_id)  group2:2(group_id) 2(member count)
user2:2(user_id)  group3:3(group_id) 2(member count)
user3:3(user_id)  group3:3(group_id) 2(member count)
user3:3(user_id)  group2:2(group_id) 2(member count)

是否可以使用单一查询或其他更好的方式?

2 个答案:

答案 0 :(得分:1)

它有可能是一个非常可怕的查询,它会像这样严肃地建议做不同的事情:(

SELECT users.user_id,groups.group_id,(SELECT COUNT(*) FROM user_group WHERE user_group.group_id=groups.group_id) FROM groups INNER JOIN user_group ON groups.group_id=user_group.group_id INNER JOIN users ON user_group.user_id=users.user_id ORDER BY users.user_id,groups.group_id ASC

答案 1 :(得分:0)

SELECT A.user_id, A.group_id, B.count FROM user_group A 
LEFT JOIN (
   select group_id, count(*) as count FROM user_group GROUP BY group_id) B 
ON A.group_id = B.group_id