我有三张桌子:
的作用
名字
usr_role
uid,摆脱
USR
uid,用户名,名字
我想加入带有角色表的usr表,并列出第三列中所有用户的所有角色名称,以逗号分隔
例如
uid, username, firstname, roles 1, user1, name1, role_name1, role_name2 2, user2, name2, role_name3, role_name4, role_name 5
我可以通过以下方式加入表:
SELECT DISTINCT u.uid AS userid, u.username AS Username,
u.firstname AS Name, r.name AS Role
FROM usr u LEFT JOIN usr_role
ON u.uid=usr_role.uid LEFT JOIN role r
ON r.rid=usr_role.rid
但我似乎更进一步
答案 0 :(得分:0)
SELECT u.uid AS userid, u.username AS Username, u.firstname AS Name,
GROUP_CONCAT(r.name) AS Role
FROM usr u LEFT JOIN usr_role ur
ON u.uid = ur.uid LEFT JOIN role r
ON ur.rid = r.rid
GROUP BY u.uid, u.username, u.firstname
示例输出:
| userid | Username | Name | Role | |--------|----------|-----------|-------------| | 1 | john | John | role1,role3 | | 2 | jane | Jane | role2 |