转换sql子查询加入

时间:2013-04-29 15:28:41

标签: mysql sql join subquery

您好我正在尝试将以下子查询转换为仅使用连接但在转换中存在一些问题并且结果过滤不正确。需要帮助找出问题或加入正确的查询。带有子查询的Sql工作正常。

SELECT ev1.eventgender,ev1.distance,ev1.style FROM events ev1 
JOIN results re1 ON ev1.eventid = re1.eventid 
JOIN competitors cm1 on re1.competitornum = cm1.competitornum
WHERE cm1.countrycode = 'AUS'
AND ev1.eventid NOT  In (SELECT ev2.eventid FROM events ev2
                         JOIN results re2 ON ev2.eventid = re2.eventid 
                         JOIN Competitors cm2 ON re2.competitornum = cm2.competitornum 
                         WHERE cm2.countrycode = 'AUS'
                         AND re2.place IN (1,2,3))

我尝试了以下查询,但结果不正确

SELECT ev1.eventgender,ev1.distance,ev1.style FROM events ev1 
LEFT OUTER JOIN results re1 
     ON ev1.eventid = re1.eventid 
     AND re1.place Not in (1,2,3)
JOIN Competitors cm1 ON re1.competitornum = cm1.competitornum
AND cm1.countrycode = 'AUS'
WHERE ev1.eventid IS NOT NULL
ORDER by ev1.eventgender, ev1.style

实际结果

enter image description here

预期结果

enter image description here

1 个答案:

答案 0 :(得分:0)

您的子查询不相关,因此您可以将其直接移至from子句。加入使用left outer join并检查where子句中没有匹配项:

SELECT ev1.eventgender, ev1.distance, ev1.style
FROM events ev1 JOIN
     results re1
     ON ev1.eventid = re1.eventid JOIN
     competitors cm1
     on re1.competitornum = cm1.competitornum left outer join
     (SELECT ev2.eventid
      FROM events ev2 JOIN
           results re2
           ON ev2.eventid = re2.eventid JOIN
           Competitors cm2
           ON re2.competitornum = cm2.competitornum 
      WHERE cm2.countrycode = 'AUS' AND re2.place IN (1,2,3)
     )
     on ev1.eventid = ev2.eventid
WHERE cm1.countrycode = 'AUS' and ev2.eventid is null