有两个表 tbldoctor 和 tblschedule
tbl医生
doc_id(PK) docMrId docfname
1 22 manish
2 23 rahul
3 22 ashish
4 24 ahemad
5 22 narendra
6 22 akshat
表计划
doctor_id(FK) mr_id schedule_date
1 22 2012-06-12
1 22 2012-06-13
3 22 2012-06-14
3 22 2012-06-14
4 24 2012-06-12
4 24 2012-06-12
5 22 2012-06-14
5 22 2012-06-15
5 22 2012-06-12
我想要的是所有医生ID的列表以及tblschedule表中重复的特定医生的计数,其中schedule_date参数和mr_id在这里提供,我们假设mr_id = 22和schedule_date在2012-06-01到2012-06-31之间
输出应该看起来像
doc_id docfname count
1 manish 2
3 rahul 2
5 narendra 3
6 akshat 0
最佳答案
select d.doc_id, docfname, count(mr_id) as count
from tbldoctor d
left outer join tblschedule s on s.doctor_id = d.doc_id
where mr_id = 22
and schedule_date between '2012-06-01' and '2012-06-31'
group by s.doctor_id
编辑
select d.doc_id,
docfname,
sum(case when mr_id = 22
then 1
else 0
end) as count
from tbldoctor d
left outer join tblschedule s on s.doctor_id = d.doc_id
and schedule_date between '2012-06-01' and '2012-06-31'
group by s.doctor_id
编辑2
怎么样
select d.doc_id, docfname, count(mr_id) as count
from tbldoctor d
left outer join tblschedule s on s.doctor_id = d.doc_id and mr_id = docmrid
where docmrid = 22
and (schedule_date between '2012-06-01' and '2012-06-31' or mr_id is null)
group by s.doctor_id
order by d.doc_id
关于mysql - mysql中如何使用连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11219742/