根据一个表左边连接3个表

时间:2014-11-13 15:44:48

标签: sql sql-server

我有一个过滤器表和一个名为FilterDoctors的多对多表,它将医生与过滤器相关联。

我想返回

的所有过滤器的ID
  1. 没有医生过滤(FilterDoctors.DoctorId IS NULL)
  2. 有一名与事件有关的医生,id = @IncidentId
  3. 是否有与预约有关的医生,其相关事件的身份= @IncidentId
  4. 我写了以下查询:

    SELECT Filters.filterId
    FROM Filters
      Left JOIN FilterDoctors   On FilterDoctors.filterId = Filters.filterId 
      Left JOIN IncidentDoctors On IncidentDoctors.doctorId = FilterDoctors.DoctorId
      Left JOIN Appointments    On Appointments.doctorId = FilterDoctors.DoctorId
    Where ( IncidentDoctors.IncidentId = @IncidentId
            OR Appointment.RelatedIncidentId = @IncidentId
            OR FilterDoctors.DoctorId IS NULL)
    

    不幸的是,这个查询似乎不起作用,因为多次返回相同的filterId。 我查了一下,加入的结果与医生过滤器中存在的医生有约会记录,但与我想要的事件id = @IncidentId无关。

      

    表关系为:

         

    约会N:1事件

         

    医生N:1次事件

         

    医生1:N约会

         

    过滤N:N医生

    什么是正确的查询?

1 个答案:

答案 0 :(得分:1)

以下是什么:

SELECT Filters.filterId
FROM Filters
  Left JOIN FilterDoctors   On FilterDoctors.filterId = Filters.filterId 
  Left JOIN IncidentDoctors On IncidentDoctors.doctorId = FilterDoctors.DoctorId
  Left JOIN Appointments    On ( Appointments.doctorId = FilterDoctors.DoctorId 
                                 AND Appointment.RelatedIncidentId = IncidentDoctors.IncidentId)
WHERE ( IncidentDoctors.IncidentId = @IncidentId
        OR FilterDoctors.DoctorId IS NULL)
GROUP BY Filters.filterId;