连接2个表以返回结果为零的查询

时间:2013-03-14 15:23:06

标签: mysql sql

我有2张桌子,一张叫医生,一张叫做约会。他们俩都有着共同关系的医生。我需要能够生成医生ID列表以及为每位医生预约的次数,无需预约。 (参见表格内容的图片)

enter image description here

使用下面的代码我可以获得医生名单id和约会数量,但它不会显示医生列表中的ZERO约会医生。我需要做哪些修改?

SELECT doctor_id, COUNT(DISTINCT appt_time) AS No_APP FROM appointment GROUP BY doctor_id;

这是我从中得到的

enter image description here

4 个答案:

答案 0 :(得分:5)

尝试:

SELECT doctor.doctor_id, COUNT(appointment.appt_time) AS No_APP 
FROM doctor
LEFT JOIN appointment 
ON appointment.doctor_id = doctor.doctor_id
GROUP BY doctor.doctor_id;

答案 1 :(得分:1)

使用左连接:

SELECT doctor.doctor_id, COUNT(appt_time) AS No_APP FROM doctor LEFT JOIN appointment ON doctor.doctor_id = appointment.doctor_id GROUP BY doctor.doctor_id;

它应该做的伎俩

答案 2 :(得分:0)

这应该有效:

select 
  d.doctor_id
  ,count(distinct a.appt_time) as No_APP 
from doctor d 
left join appointment a on d.doctor_id=a.doctor_id
group by d.doctor_id

答案 3 :(得分:0)

使用左连接:

SELECT doctor.doctor_id, COUNT(DISTINCT appt_date, appt_time) AS No_APP 
FROM doctor 
LEFT JOIN appointment
ON doctor.doctor_id = appointment.doctor_id
GROUP BY doctor_id;