2013-05-10 144 views
0

我試圖找到比賽裁判(誰是官方)也爲主隊和客隊(請參閱下面的關係圖)提供醫療服務的比賽。SQL查詢問題

我已經試過這一點,但它不返回任何記錄:

select matches.id, 
matches.home, 
matches.away, 
matches.referee 
from matches 
join officials on officials.staffid = matches.referee 
join medicalservices on medicalservices.team in (matches.home, matches.away) 
where medicalservices.team = matches.home 
and medicalservices.team = matches.away; 

我猜它不返回,因爲最後兩行的記錄,但我不知道怎麼回事,我可以確保同一位官員爲兩隊參賽者提供醫療服務。

下面是引用關係圖:

enter image description here

回答

1

你需要加入醫療服務兩次,第一次發現提供給主隊服務,並再次找到提供給客隊的服務。然後你可以檢查提供給每個球隊的服務是否由同一裁判。

你也不需要官方表。

select matches.id, 
matches.home, 
matches.away, 
matches.referee 
from matches 
join medicalservices home_medservices on home_medservices.team = matches.home 
join medicalservices away_medservices on away_medservices.team = matches.away 
where home_medservices.official = matches.referee 
    and away_medservices.official = matches.referee 
+0

這些都沒有給出預期的輸出。 – Martin 2013-05-10 21:02:59

+0

@Tangler對不起,試試我更新的答案。我之前沒有閱讀過你的連接條款,並且認爲它是正確的。 – Brandon 2013-05-10 21:04:37

+0

謝謝,現在工作。 – Martin 2013-05-10 21:15:39