使用group_concat连接查询,重复值

时间:2014-03-01 16:30:34

标签: mysql sql aggregate-functions

我的下面的查询无法正常工作,因为我接受基本上我愿意以逗号分隔的方式获取每位医生的所有记录,并且还可以获取每个医生约会的具体月份,但查询重复逗号分隔的专业。

select  d.doctorFName,d.doctorLName ,count(ap.appointmentID) totalap,
GROUP_CONCAT(s.speciality) specialities
FROM  tbl_doctors d
INNER JOIN  tbl_doctor_speciality  ds ON (d.doctorID = ds.doctorID)
INNER JOIN tbl_speciality  s ON (s.spID = ds.spID)
Inner join tbl_appointment ap on (ap.doctorID = d.doctorID)
Inner join tbl_patients p on p.patientID = ap.patientID 
GROUP BY d.doctorID

我的每个医生和他们的专业都用逗号分隔

select  d.doctorFName,d.doctorLName ,
GROUP_CONCAT(s.speciality) specialities
FROM  tbl_doctors d
INNER JOIN  tbl_doctor_speciality  ds ON (d.doctorID = ds.doctorID)
INNER JOIN tbl_speciality  s ON (s.spID = ds.spID)
GROUP BY d.doctorID 

但是当我添加联接预约其重复专业时,下面是我的数据库,我希望你能通过查询理解数据。我做错了吗?以及我如何使用

DATE_FORMAT(ap.appDate, '%Y-%m') = '2013-10'

以上查询因为它得到错误

1 个答案:

答案 0 :(得分:2)

尝试使用group_concat中的DISTINCT,内部联接一对多将生成笛卡尔积,这样您就可以获得重复值

select  d.doctorFName,d.doctorLName ,count(ap.appointmentID) totalap,
GROUP_CONCAT(DISTINCT  s.speciality) specialities
FROM  tbl_doctors d
INNER JOIN  tbl_doctor_speciality  ds ON (d.doctorID = ds.doctorID)
INNER JOIN tbl_speciality  s ON (s.spID = ds.spID)
Inner join tbl_appointment ap on (ap.doctorID = d.doctorID)
Inner join tbl_patients p on p.patientID = ap.patientID 
GROUP BY d.doctorID