简体   繁体   English

MySQL LIMIT在GROUP BY的ORDER中

[英]Mysql LIMIT in ORDER in GROUP BY

I have this game log table: 我有此游戏日志表:

+---------+------+-------+
| game_id | user | score |
+---------+------+-------+
| 1       | Nick | 10    |
| 1       | Bob  | 15    |
| 2       | Nick | 15    |
| 2       | Bob  | 10    |
| 3       | Nick | 20    |
+---------+------+-------+

In each game the winner is only one user, who get the greatest score. 在每场比赛中,获胜者只有一个,得分最高。 And I'm trying select each game with its winner, for example: 我正在尝试选择每个游戏及其赢家,例如:

+---------+--------+
| game_id | winner |
+---------+--------+
| 1       | Bob    |
| 2       | Nick   |
| 3       | Nick   |
+---------+--------+

But all of my trying is without result. 但是我所有的尝试都是没有结果的。 Could anyone help me? 有人可以帮我吗?

You can use the following query: 您可以使用以下查询:

SELECT g1.game_id, g1.user AS winner
FROM games AS g1
INNER JOIN (
   SELECT game_id, MAX(score) AS maxScore
   FROM games
   GROUP BY game_id 
) AS g2 ON g1.game_id = g2.game_id AND g1.score = g2.maxScore

Demo here 在这里演示

One approach is to first create a temporary table which contains the game id along with the maximum score for that game id. 一种方法是首先创建一个临时表,其中包含游戏ID以及该游戏ID的最高分。 This is what the inner query in my answer below does. 这就是我下面的答案中的内部查询。 Then this can be joined back to your original table to get the user associated with that game id and winning score. 然后,可以将其重新连接到原始表中,以获取与该游戏ID和获胜分数相关的用户。

SELECT t.game_id, t.user AS winner
FROM gamelog t1 INNER JOIN
(
    SELECT g.game_id, MAX(g.score) AS maxscore
    FROM gamelog g
    GROUP BY g.game_id
) t2
ON t1.game_id = t2.game_id AND t1.score = t2.maxscore

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM