0

我有这些表(简化):

Appointment(
    INT idAppointment,
    DATETIME start,
    DATETIME end)

AppointmentInvolved(
    INT idAppointment,
    INT idInvolved)

Involved(
    INT idInvolved,
    VARCHAR name,
    INT type,
    INT idIncident)

Incident(
    INT idIncident,
    VARCHAR description)

发生了一起事件,可能涉及到几个事件。每个 Involved 可以有多个约会,并且每个约会可以由多个 Involved 参加。涉及的有类型(本例中,principal=1,secondary=2)。

给定一个 idAppointment,我需要知道参与该事件的负责人,无论他是否要参加该特定约会。

至今:

SELECT(*)
FROM Appointments a
INNER JOIN (AppointmentInvolved ai) ON ai.idAppointment = a.idAppointment,
INNER JOIN (Involved i) ON i.idInvolved = ai.idInvolved,
INNER JOIN (Incident in) ON i.idIncident = in.idIncident,
WHERE a.idAppointment = <WHATEV>
WHERE in.type=1

除非所涉及的校长要去参加那个约会,否则这显然是行不通的。这是某种自我加入吗?我真的不需要 Incident 表,因为参与人员可以通过 idInvolved 直接关联。

谢谢!

4

1 回答 1

0
SELECT * 
FROM Involved I
WHERE I.type=1 
  AND I.idIncident IN (SELECT I2.idIncident 
                       FROM AppointmentInvolved AI
                          INNER JOIN Involved I2 ON AI.idInvolved = I2.idInvolved
                          WHERE AI.idAppointment=<WHATEV>)
于 2012-08-09T15:16:40.453 回答