查询不返回所有记录

时间:2014-03-01 17:18:12

标签: mysql sql

下面的

enter image description here是我的查询,我愿意每个月取一位医生和他们的预约

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

我愿意通过

获取记录
DATE_FORMAT(ap.appDate, '%Y-%m') = '2013-10'

如果某人医生没有任何特定月份的预约然后返回0医生排,我怎么能这样做?

我的愿望

enter image description here

2 个答案:

答案 0 :(得分:0)

尝试使用LEFT OUTER JOIN,如下所示。如果您需要更多帮助,则需要发布一些样本数据和所需的输出。

SELECT d.doctorFName,
    d.doctorLName,
    count(ap.appointmentID) totalap,
    GROUP_CONCAT(DISTINCT  s.speciality) specialities,
    SUM(CASE WHEN YEAR(ap.appDate) = 2013 AND MONTH(ap.appDate) = 10 THEN 1 
             ELSE 0 END) Oct2013,
    SUM(CASE WHEN YEAR(ap.appDate) = 2013 AND MONTH(ap.appDate) = 11 THEN 1 
             ELSE 0 END) Nov2013,
    SUM(CASE WHEN YEAR(ap.appDate) = 2013 AND MONTH(ap.appDate) = 12 THEN 1 
             ELSE 0 END) Dec2013
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)
    LEFT OUTER JOIN tbl_appointment ap on (ap.doctorID = d.doctorID)
    LEFT OUTER JOIN tbl_patients p on p.patientID = ap.patientID 
GROUP BY d.doctorID

答案 1 :(得分:0)

在Appt表上尝试左连接

SELECT d.doctorFName,d.doctorLName ,count(ap.appointmentID) totalap,
     GROUP_CONCAT(DISTINCT  s.speciality) specialities,DATE_FORMAT(ap.appDate, '%Y-%m') appMonth
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)
LEFT JOIN tbl_appointment ap on (ap.doctorID = d.doctorID)
INNER JOIN tbl_patients p on p.patientID = ap.patientID 
GROUP BY d.doctorID,appMonth

这将首先显示按医生分组,然后按appDate月分组... 如果博士一个月没有appt它会显示零 我相信这对你有用