如何在我的SQL中使用连接?

时间:2012-06-27 05:08:53

标签: mysql

有两个表tbldoctor和tblschedule

tbldoctor

 doc_id(PK)    docMrId        docfname
      1          22             manish
      2          23             rahul
      3          22             ashish
      4          24             ahemad
      5          22             narendra
      6          22             akshat

tblschedule

  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

我想要的是所有doctorid的列表以及在tblschedule表中重复的特定医生的计数,其中提供了schedule_date参数和mr_id,我们假设mr_id = 22和schedule_date在2012-06-01到2012-06-31之间< / p>

输出应该看起来像

  doc_id         docfname      count
    1               manish       2
    3               rahul        2
    5               narendra     3
    6               akshat       0

4 个答案:

答案 0 :(得分: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
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

SQLFiddle example

编辑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

SQLFiddle example

答案 1 :(得分:1)

不是100%肯定我已经了解你,但是这会给你一份所有医生ID的清单,以及两个给定日期之间每个医生ID的计划项目数。

SELECT tbldoctor.doc_id, COUNT(*) cnt
FROM tbldoctor d INNER JOIN tblschedule s
    ON d.doc_id = s.doctor_id
WHERE s.schedule_date BETWEEN '2012-06-12' AND '2012-06-15'
GROUP BY tbldoctor.doc_id

答案 2 :(得分:0)

SELECT * FROM `tbldoctor` JOIN `tblschedule` ON `tblschedule`.doctor_id(FK) = `tbldoctor`.doc_id(PK)

答案 3 :(得分:0)

SELECT tbldoctor.doc_id, COUNT(*) cnt FROM tbldoctor d INNER JOIN tblschedule s     ON d.doc_id = s.doctor_id WHERE s.schedule_date BETWEEN '2012-06-12' AND '2012-06-15' GROUP BY tbldoctor.doc_id