我有两张桌子
player1有行username,score,game_id,...
player2有行用户名,得分,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
答案 0 :(得分: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
正如大流士所说,你可能希望根据抽奖情况调整CASE陈述,你可以将其改为:
CASE WHEN p1.score > p2.score THEN p1.username WHEN p1.score < p2.score THEN p2.username ELSE 'Draw' END AS winner
这实际上取决于您希望在该场景中显示的内容。