1

嗨,我正在尝试将以下子查询转换为仅使用联接,但在转换中存在一些问题,并且结果被错误地过滤。需要帮助来找出问题或正确的连接查询。带有子查询的 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

实际结果

在此处输入图像描述

预期结果

在此处输入图像描述

4

1 回答 1

0

您的子查询不相关,因此您可以将其直接移至from子句。将其加入 usingleft 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
于 2013-04-29T15:34:54.970 回答