加入子查询时使用if条件

时间:2019-04-17 15:27:48

标签: mysql mysqli

如果Events.Type字段等于1,则在以下查询中我需要使用XXXXX的查询部分是这样的:

ON Stages.ID = Abandonments.IDstage

如果事件是2,则输入XXXXX的查询部分应如下所示:

ON Stages.ID > Abandonments.IDstage

查询

SELECT
*,
  Events.Type
FROM Participants
  INNER JOIN Times
    ON Participants.ID = Times.IDparticipant
  INNER JOIN Events
    ON Events.ID = Participants.IDevent
    AND Events.ID = Times.IDevent
  INNER JOIN Stages
    ON Events.ID = Stages.IDevent
    AND Stages.ID = Times.IDstage
  LEFT OUTER JOIN (SELECT
      Retired.ID,
      Retired.IDstage,
      Retired.IDparticipant,
      Retired.IDevent
    FROM Retired) Abandonments
    XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX
    AND Participants.ID = Abandonments.IDparticipant
    AND Events.ID = Abandonments.IDevent
WHERE Times.IDevent = 31
AND Times.IDstage = 156
ORDER BY Participants.ID

谢谢

1 个答案:

答案 0 :(得分:0)

您的SQL查询中有很多X,并且没有显示您要构建的限定符,因此我不太了解您要达到的意图。

但是,您在问题中描述了解决方案。

因此:

ON ((Stages.ID = Abandonments.IDstage AND Events.Type = 1) OR 
   (Stages.ID > Abandonments.IDstage AND Events.Type = 2))

如果这些定义的参数都不为真(例如Events.Type = 3),则需要添加限定符或错误的返回值以排除整个JOIN

ON ((Stages.ID = Abandonments.IDstage AND Events.Type = 1) OR 
   (Stages.ID > Abandonments.IDstage AND Events.Type = 2)) OR 2=1