簡體   English   中英

如何在SQL中執行以下聯接?

[英]How do I perform the following join in SQL?

假設我有下表GAME

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
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

使用表別名“ P”代表“玩家”,使用“ O”代表“對手”

Marc指出,這可能因數據庫而異。 替代的聯接語法(在您偶爾使用的情況下,例如舊的Informix)將是在from上列出兩個表,並將join-on子句移到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應該最適合。

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

編輯:使查詢像應該的那樣工作。 但是請查看Rup的答案,以更好地完成它。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM