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

时间:2016-11-04 01:54:52

标签: 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

获得分数最高的每个级别所需的SQL查询是什么?

结果应为:

id | user_id | level | score
4  | Mark    | 1     | 60
3  | John    | 2     | 30
6  | David   | 3     | 80
9  | David   | 4     | 50

谢谢

3 个答案:

答案 0 :(得分:4)

如果你想获得关系,那么你可以这样做:

select s.*
from scores s
where s.score = (select max(s2.score) from scores s2 where s2.level = s.level);

您可以通过聚合来获得每个级别一行:

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;

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

答案 1 :(得分:0)

在子查询中按分数desc排序,然后逐级选择max(score)。

select id, user_id , level , max(score) as score
from
(select * from scores order by score desc)A 
group by level  

答案 2 :(得分:0)

如果您只想要首先达到最高分的用户(每个级别没有关系):

select *
from users u1
where id = (
    select id
    from users u2
    where u2.level = u1.level
    order by score desc, id asc
    limit 1
)

您应该拥有索引(id)(level, score, id)