GROUP_CONCAT 在两个不同的表上
GROUP_CONCAT on two different tables
我有三个表:
员工
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 以获得我想要的输出?
您可以像这样构建最终结果:
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;
所有这些单引号和不寻常的字符可能存在拼写错误。
我有三个表:
员工
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 以获得我想要的输出?
您可以像这样构建最终结果:
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;
所有这些单引号和不寻常的字符可能存在拼写错误。