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

9

我有一张用户表格,记录了他们在游戏的每个等级中的得分:

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

谢谢您


1
这是一个简单的“group by”查询。你能发一下你的尝试吗? - Vamsi Prabhala
相关:https://dev59.com/aXM_5IYBdhLWcg3wmkQK - jdhao
3个回答

14

如果您想获取关联内容,那么可以尝试以下方法:

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
在子查询中按照分数降序排序,然后按级别分组选择最高分。
select id, user_id , level , max(score) as score
from
(select * from scores order by score desc)A 
group by level  

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)


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接