我有一个过滤器表和一个名为FilterDoctors的多对多表,它将医生与过滤器相关联。
我想返回 :
的所有过滤器的ID我写了以下查询:
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医生
什么是正确的查询?
答案 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;