简体   繁体   中英

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. 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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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