我有三张桌子:
人员
id name
1 Alex
2 John
3 Peter
staff_roles
id role_name
1 Barber
2 Driver
assigned_roles
id staff_id role_id
1 1 1
2 1 2
3 2 1
4 3 2
我想获得输出smth。像:
name roles
Alex [{'id':'1','role_name':'Barber'},{'id':'2','role_name':'Driver'}]
John [{'id':'1','role_name':'Barber'}]
Peter [{'id':'2','role_name':'Driver'}]
我正在做:
SELECT
staff.name,
GROUP_CONCAT(DISTINCT assigned_roles.role_id) as roles
FROM staff
LEFT JOIN assigned_roles
ON assigned_roles.staff_id = staff.id
LEFT JOIN roles
ON roles.id = assigned_roles.role_id
GROUP BY
staff.id
但是如何将角色名称添加到GROUP_CONCAT以获得我想要的输出?
答案 0 :(得分:1)
你可以像这样构建最终结果:
SELECT s.name,
CONCAT('[',
GROUP_CONCAT(DISTINCT '{''id'':''', ar.role_id, ''',''role_name'':''', r.role_name, '''}'),
']')
FROM staff s LEFT JOIN
assigned_roles ar
ON ar.staff_id = s.id LEFT JOIN
roles r
ON r.id = ar.role_id
GROUP BY s.id;
可能存在所有单引号和不寻常字符的拼写错误。