简体   繁体   English

将SQL子查询转换为联接

[英]Convert sql sub query to join

Hi I am trying to convert following sub query to just use joins but in the conversion there are some issue and the results are getting filtered incorrectly. 嗨,我正在尝试将以下子查询转换为仅使用联接,但在转换中存在一些问题,结果过滤不正确。 Need help to figure out the problem or the correct query with join. 需要帮助以找出问题或使用联接的正确查询。 The Sql with the sub query is working fine. 带有子查询的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))

I have tried the following query but the result is not correct 我已经尝试了以下查询,但结果不正确

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

Actual Result 实际结果

在此处输入图片说明

Expected Result 预期结果

在此处输入图片说明

Your subquery is not correlated, so you can move it directly to the from clause. 您的子查询不相关,因此您可以将其直接移至from子句。 Join it in using left outer join and check in the where clause for no matches: 使用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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM