2013-04-29 94 views
1

您好我想轉換下面的子查詢,只是使用連接,但在轉換中有一些問題,結果得到過濾不正確。需要幫助來找出問題或加入正確的查詢。子查詢Sql工作正常。轉換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

你在使用 – 2013-04-29 15:32:37

+0

我使用MySQL的 – 2013-04-29 15:38:29

+1

@Evan請詳細RDBMS - 爲什麼你認爲這兩件事情有什麼不同? – 2013-04-29 15:41:03

回答

0

您的子查詢不相關,因此您可以將其直接移至from子句。加入它使用left outer joinwhere子句中檢查是否有匹配:

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