MySQL:加入三个表并连接分组结果

时间:2016-04-13 02:09:03

标签: php mysql database

我有三张桌子'医生' '特色'和' doctor_specialities':

doctors 
-id
-doctor_name

specialities 
-id
-speciality_name

doctor_specialities 
-id
-doctor_id
-speciality_id

我希望将所有医生以及他们的专业名称和专业ID归还给我。医生可以有多种专业。

结果集应该类似于:

id       |       doctor_name       |       speciality_id       |       speciality_name
--------------------------------------------------------------------------------------
1        |       John              |       5,3                 |       Speciality1,Speciality2
3        |       Tim               |       3                   |       Speciality2
6        |       David             |       NULL                |       NULL

我在下面尝试了查询:

SELECT d.id ,d.doctor_name, s.speciality_name, s.id
AS speciality_id
FROM api_doctors d
LEFT JOIN api_doctor_specialities ds
ON ds.doctor_id = d.id
LEFT JOIN api_specialities s
ON s.id = ds.speciality_id
GROUP BY d.id

但在这种情况下,我将获得单一专业。

1 个答案:

答案 0 :(得分:4)

您正在寻找的是名为GROUP_CONCAT的MySQL函数,它返回连接结果或NULL。默认分隔符是逗号,因此此查询的结果应与您想要的结果集匹配。

SELECT d.id, d.doctor_name, GROUP_CONCAT(s.speciality_name) AS speciality_name, GROUP_CONCAT(s.id) AS speciality_id
FROM api_doctors d
LEFT JOIN api_doctor_specialities ds
ON ds.doctor_id = d.id
LEFT JOIN api_specialities s
ON s.id = ds.speciality_id
GROUP BY d.id

SQL Fiddle

上的架构和查询