如何从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
答案 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)
它假设平局对两位球员来说都是一场胜利。
如果您想获得玩家及其获胜次数,可以使用此查询:
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
就是他们的胜利或关系数。