[英]Get Max value and corresponding column
How can I get corresponding columns from a max query in mysql? 如何从mysql中的max查询中获取相应的列? I want find out how many wins a player has. 我想知道一个球员有多少个胜利。 I will find that out by doing a count of the number of games that player has won. 通过计算玩家赢得的游戏数量,我会发现这一点。 The will be done by selecting the max value per game and resulting player_id. 通过选择每个游戏的最大值和最终的player_id来完成。 However I am not sure how to get the corresponding player_id. 但是我不确定如何获取相应的player_id。
I have 我有
id | game_id | player_id | score
1 | 1 | 1 | 254
2 | 1 | 2 | 194
3 | 2 | 1 | 432
4 | 2 | 2 | 298
This query should get what you need: 这个查询应该得到您所需要的:
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)
It assumes that a tie is a win for both players. 假设平局对双方都赢了。
If you want to get just the player and their number of wins, you can use this query: 如果您只想获得球员及其获胜次数,则可以使用以下查询:
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
Just replace {player_id}
with the player you're looking for and wins
is their number of wins or ties. 只需将{player_id}
替换为您要寻找的球员, wins
就是他们的获胜或平局数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.