2011-03-02 29 views
0

假設我有如下表GAME如何在SQL中執行以下連接?

match_id, user_id, score 
1, 10, 45 
1, 11, 57 
2, 10, 39 
2, 14, 63 

現在我想做一個查詢它獲取播放器10,並提出他的得分,他的對手是這樣

match_id, user_id, score, opponent_id, opponent_score 
1, 10, 45, 11, 57 
2, 10, 39, 14, 63 
+2

你有沒有考慮過改變你的表,所以它是(match_id,player1_id,player1_score,player2_id,player2_score)?你的問題似乎假設總是有兩名球員。如果你不能做出這樣的假設,那麼在比賽中有兩名以上球員的情況下你想要返回什麼? – tenfour 2011-03-02 12:14:52

+0

什麼數據庫系統和你使用的是什麼版本? – 2011-03-02 12:15:15

+1

這看起來很像我星期五 – Woot4Moo 2011-03-02 12:29:47

回答

2
select P.match_id, 
     P.user_id, 
     P.score, 
     O.user_id as opponent_id, 
     O.score as opponent_score 
    from GAME P 
    join GAME O 
    on O.match_id = P.match_id 
    and O.user_id <> P.user_id 
    where P.user_id = 10 
order by P.match_id 

,O-關於「對手」

馬克指出,這可以通過數據庫而有所不同。替代連接語法 - 在您使用的機會不多時,一箇舊的Informix--將在from上列出這兩個表並將該連接子句移動到where,例如

from GAME P, GAME O 
    where O.match_id = P.match_id 
    and O.user_id <> P.user_id 
    and P.user_id = 10 

join應該適用於大多數。

1
SELECT 
    a.match_id, 
    a.user_id AS user_id, 
    a.score AS score, 
    b.user_id AS opponent_id, 
    b.score AS opponent_score 
FROM 
    game a 
JOIN 
    game b 
ON 
    a.match_id = b.match_id 
AND 
    a.user_id <> b.user_id 
WHERE 
    a.user_id = 10 

隨着樂曲編輯:使查詢工作就像它應該。但看看魯普的答案,看看它做得更好。使用表別名P代表「播放」

+0

的家庭作業,你真的嘗試過嗎? – tenfour 2011-03-02 12:17:41

+0

mmh,在我看到Rup的答案後,我不再確定了。那個「O.user_id <> P.user_id」也是必需的。所以,不,我沒有運行它,對不起,Rup給出了更好的答案。 – Enduriel 2011-03-02 12:20:36

1
select 
    U.match_id, 
    U.user_id, 
    U.score, 
    O.user_id as opponent_id, 
    O.score as opponent_score 
from GAME U 
    inner join GAME O on 
     U.match_id = O.match_id and 
     U.user_id <> O.user_id 
where U.user_id = 10