php – MySQL列出用户及其组
作者:互联网
在MySql数据库中我有表用户
user_id | user_name
--------+----------
1 | Joe
2 | Anna
3 | Max
表组
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
解决方法:
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
标签:concat,php,mysql,group-concat 来源: https://codeday.me/bug/20190902/1789433.html