在MySql数据库中,我有表user
user_id | user_name
--------+----------
1 | Joe
2 | Anna
3 | Max
表group
group_id | group_name
---------+----------
1 | Red
2 | Blue
3 | Green
表group_member
group_member_id | user_id | group_id
----------------+---------+---------
1 | 1 | 2
2 | 3 | 2
3 | 1 | 3
3 | 2 | 1
所以... Red组的成员是Anna,Green gorup的成员是Joe,Blue组的成员是Joe和max。
如何获取用户及其群组列表
User | Group
------+------------
Joe | Green, Blue
Anna | Red
Max | Blue
答案 0 :(得分:5)
您可以使用MySQL的GROUP_CONCAT
功能完成它。请注意,这使您的查询不可移植(因为使用MySQL扩展):
SELECT user_name, GROUP_CONCAT(group_name)
FROM user
JOIN group_member USING (user_id)
JOIN group USING (group_id)
GROUP BY
user_id
我假设你在表上有合理的主键/唯一键(例如,给定的用户名不能在同一组中列出两次)。
答案 1 :(得分:0)
SELECT u.user_name, GROUP_CONCAT(g.group_name)
FROM `user` u
inner JOIN group_member gm on gm.user_id = u.user_id
inner JOIN `group` g on g.group_id = gm.group_id
group by u.user_id
答案 2 :(得分:0)
select u.user_name as users, group_concat(g.group_name) as groups
from `user` u
join group_member gm on gm.user_id = u.user_id
join `group` g on g.group_id = gm.group_id
group by u.user_id;