【问题标题】:How to use a left join and self join in SQL Server in a single query?如何在单个查询中使用 SQL Server 中的左联接和自联接?
【发布时间】:2026-01-07 12:10:02
【问题描述】:

我有以下表格:

  1. tbl_Patient_Master

  1. tbl_Doctor_Master

  1. tbl_Appointment_Creation

我想要的结果如下:

【问题讨论】:

  • 到目前为止你尝试过什么?请显示一些代码。
  • 这是一个JOIN,来自医生到预约预约到患者。你试过什么?
  • 你认为你为什么需要自我加入?
  • 您可以使用select from tbl_Appointment_creation,然后使用left join to tbl_patient_masterleft join to tbl_doctor_master。您不需要自我加入
  • 我想用同一个医生的名字对它们进行分组。请参考问题所附的最后一张图片。

标签: sql-server join


【解决方案1】:

你不需要SELF JOIN

SELECT A.Booking_ID, D.Doctor_name, P.Patient_Name, A.Booking_Date, A.Comments 
FROM Appointment A
LEFT JOIN Doctor D ON A.Doctor_ID = D.Doctor_ID
LEFT JOIN Patient ON A.Patient_ID = P.Patient_ID
GROUP BY D.Doctor_name, P.Patient_Name, A.Booking_Date, A.Booking_ID, A.Comments

【讨论】:

  • 您的查询提供了医生和患者姓名列,但我想用相同的医生姓名对它们进行分组。请参考问题所附的最后一张图片。
  • @FlaSh9293 请检查并告诉我它是否有效?
  • 列 'tbl_Appointment_Creation.Booking_Date' 在选择列表中无效,因为它不包含在聚合函数或 GROUP BY 子句中。
  • @FlaSh9293 请立即查看。
【解决方案2】:

要获得具有相同doctorpatients,我们需要首先获得具有相同医生的appointments

select t1.Booking_Id, t2.Doctor_Name, t3.Patient_name, t1.Date, t1.Comments
from Appointment t1
join Doctor t2 on t1.Doctor_ID = t2.Doctor_ID
join Patient t3 on t1.Patient_ID = t3.Patient_ID
inner join ( 
    select count(1), d.Doctor_name
    from Appointment a
    join Doctor d on a.Doctor_ID = d.Doctor_ID
    join Patient p on a.Patient_ID = p.Patient_ID
    group by a.Doctor_name
    having count(1) > 1) t on t.Doctor_name = t2.Doctor_name

【讨论】:

    【解决方案3】:
    select A.Booking_ID as Booking_ID
         , B.Doctor_Name as Doctor_Name
         , C.Patient_Name as Patient_Name
         , A.Booking_Date as Date
         , A.Comments as Comments
      from Appointment_Creation A
         , Doctor B
         , Patient C
     where A.Doctor_ID = B.Doctor_ID
       and A.Patient_ID = C.Patient_ID
    

    不需要使用左连接,但我建议使用外键

    【讨论】:

    • 您的查询提供了医生和患者姓名列,但我想用相同的医生姓名对它们进行分组。请参考问题所附的最后一张图片。