2

我有两张桌子。
player1 有行 username, score, game_id, ...
player2 有行 username, score, game_id...
你如何为同一个 game_id 选择得分最高的用户名?

我所拥有的是

SELECT player1.username winning,
  player1.points,
  player1.game_id 
FROM player1 
INNER JOIN player2 ON player1.game_id = player2.game_id
WHERE player1.points > player2.points

SELECT player2.username winning,
  player2.points,
  player2.game_id 
FROM player1 
INNER JOIN player2 ON player1.game_id = player2.game_id
WHERE player2.points > player1.points  
4

1 回答 1

5

这应该这样做:

SELECT
    game_id, 
    CASE WHEN p1.score > p2.score THEN p1.username ELSE p2.username END AS winner
FROM
    player1 p1
INNER JOIN
    player2 p2 ON p1.game_id = p2.game_id
ORDER BY 
    p1.game_id ASC

正如 Darius 所说,您可能希望根据平局的情况调整 CASE 语句,您可以将其更改为如下内容:

CASE WHEN p1.score > p2.score THEN p1.username WHEN p1.score < p2.score THEN p2.username ELSE 'Draw' END AS winner

这实际上取决于您要在该场景中显示的内容。

于 2013-02-20T01:26:27.583 回答