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