[英]MySQL - How to select rows with max value of a field
我有一张用户表,其中包含游戏每个级别的得分:
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
谢谢
如果您想建立联系,则可以执行以下操作:
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;
这会将用户(如果有多个)组合到一个字段中。
在子查询中按分数desc排序,然后按级别选择max(score)分组。
select id, user_id , level , max(score) as score
from
(select * from scores order by score desc)A
group by level
如果只希望用户谁先获得最高分数(每个级别没有关系):
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.