MySQL - 如何选择字段最大值的行

Mr.*_*ssy 5 mysql sql

我有一个用户表格,其中包含游戏每个级别的分数:

id | user_id | level | score
1  | David   | 1     | 20
2  | John    | 1     | 40
3  | John    | 2     | 30
4  | Mark    | 1     | 60
5  | David   | 2     | 10
6  | David   | 3     | 80
7  | Mark    | 2     | 20
8  | John    | 3     | 70
9  | David   | 4     | 50
10 | John    | 4     | 30
Run Code Online (Sandbox Code Playgroud)

每个级别需要获取的 SQL 查询是什么,谁的分数最高?

结果应该是:

id | user_id | level | score
4  | Mark    | 1     | 60
3  | John    | 2     | 30
6  | David   | 3     | 80
9  | David   | 4     | 50
Run Code Online (Sandbox Code Playgroud)

谢谢

Gor*_*off 9

如果你想建立关系,那么你可以这样做:

select s.*
from scores s
where s.score = (select max(s2.score) from scores s2 where s2.level = s.level);
Run Code Online (Sandbox Code Playgroud)

您可以通过聚合以下内容在每个级别获得一行:

select s.level, s.score, group_concat(s.user_id)
from scores s
where s.score = (select max(s2.score) from scores s2 where s2.level = s.level)
group by s.level, s.score;
Run Code Online (Sandbox Code Playgroud)

这将用户(如果有多个)合并到一个字段中。