mysql - mysql中如何使用连接?

标签 mysql

有两个表 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

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

关于mysql - mysql中如何使用连接?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11219742/

相关文章:

mysql - 为什么参数绑定(bind)在 order by 或 select 语句中不起作用?

mysql - Doctrine 的 findBy*() 中的 LIKE 和 % 通配符

mysql - 如何通过SQL去除停用词

mysql - Grails Web 应用程序为远程数据库生成 MySql 重复条目,但不为本地测试数据库生成

mysql - 更改查询的输出 - 查找替换

mysql - CASE 内带有条件的 SELECT 计数

java - JDBC 中的负载平衡和复制

python - 检查带有SELECT的INSERT在MySQL中是否成功

php - MySql + InnoDB + PHP 单引号判别?

php - 在多对多多态中搜索具有相同标签的所有行