2

如何从 mysql 中的最大查询中获取相应的列?我想知道一个玩家有多少胜。我会通过计算玩家赢得的游戏数量来发现这一点。这将通过选择每场比赛的最大值和生成的 player_id 来完成。但是我不确定如何获取相应的 player_id。

我有

   id   |   game_id | player_id | score

    1   |     1     |     1     |   254
    2   |     1     |     2     |   194
    3   |     2     |     1     |   432
    4   |     2     |     2     |   298
4

1 回答 1

4

这个查询应该得到你需要的:

SELECT
    player_id, game_id, score
FROM
(
    SELECT game_id,MAX(score) AS MaxScore
    FROM games
    GROUP BY game_id
) AS Winners
JOIN games
    ON (games.game_id = Winners.game_id AND games.score = Winners.MaxScore)

它假设平局是双方玩家的胜利。

SQLFiddle

如果您只想获取玩家及其获胜次数,可以使用以下查询:

SELECT
    player_id, COUNT(*) AS wins
FROM
(
    SELECT game_id,MAX(score) AS MaxScore
    FROM games
    GROUP BY game_id
) AS Winners
JOIN games
    ON (games.game_id = Winners.game_id AND games.score = Winners.MaxScore)
WHERE player_id = {player_id}
GROUP BY player_id

只需替换{player_id}为您正在寻找的球员,wins即他们的胜利或平局数。

于 2013-03-14T20:02:44.583 回答