如何在SQL中执行以下连接?

时间:2011-03-02 12:10:11

标签: 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

3 个答案:

答案 0 :(得分: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

使用表别名P代表'玩家',O代表'对手'

Marc指出这可能因数据库而异。替代连接语法 - 关于你正在使用的机会,例如一个旧的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 :(得分: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

编辑:使查询按预期工作。但看看Rup的答案,看看它做得更好。

答案 2 :(得分: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