获取最大值和相应列

时间:2013-03-14 19:30:17

标签: mysql sql greatest-n-per-group

如何从mysql中的max查询中获取相应的列?我想知道一名球员有多少胜利。通过计算玩家赢得的游戏数量,我会发现这一点。这将通过选择每场比赛的最大值和结果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

1 个答案:

答案 0 :(得分: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就是他们的胜利或关系数。