此查询选择以下内容:
SELECT jobs.JobID, school.School_Name,
CONCAT(staff.First_Name, ' ', staff.Last_Name) AS 'Full_Name',
staff.Phone_Number, role.Role
FROM jobs
INNER JOIN school ON jobs.SchoolID=school.SchoolID
INNER JOIN staff ON jobs.StaffID=staff.staffID
INNER JOIN role ON jobs.roleID=role.roleID
ORDER BY staff.StaffID asc
JOB ID FULL NAME ROLE
------ --------- ----------
1 BOB PRINCIPLE
2 BOB TEACHER
3 JACK TEACHER
4 SARAH ACCOUNTANT
5 SARAH NURSE
但是,我希望结果看起来像:
BOB PRINCIPLE, TEACHER
JACK TEACHER
SARAH ACCOUNTANT, NURSE
我对如何做到这一点感到困惑,因为通过添加GROUP BY子句,它仅选择了第一个JobID?
感谢您的任何帮助,谢谢。
答案 0 :(得分:1)
您可以使用GROUP_CONCAT
SELECT Full_Name, GROUP_CONCAT(Role) AS Role
FROM
(
SELECT jobs.JobID, school.School_Name, CONCAT(staff.First_Name, ' ', staff.Last_Name)
AS Full_Name, staff.Phone_Number, role.Role
FROM jobs
INNER JOIN school ON jobs.SchoolID=school.SchoolID
INNER JOIN staff ON jobs.StaffID=staff.staffID
INNER JOIN role ON jobs.roleID=role.roleID
ORDER BY staff.StaffID asc
) q
GROUP BY Full_Name