[英]MySQL - selecting rows around a certain row criteria
我正在尝试仅选择某个行条件前后的相邻N行和M行,以获得针对用户个人得分的高分表(与得分高于N且得分低于M的玩家比较)。
scores ------- id:int username:varchar(120) score:int
注意:每个用户名都有多个分数。 高分数据库只是分数转储
因此,仅获取全球排名前10位的分数: SELECT max(score),username FROM scores GROUP BY username, ORDER BY score DESC
但是,我正在尝试对任何任意用户执行此操作-其中大多数用户还不够幸运,无法跻身前10名...
我如何引用某个用户分数上方的N行和M行以下,以在用户分数上方和下方抽取10个分数?
为了使N个结果高于用户,假设所有得分都不同:
select s.*
from scores
where s.score > (select s.score from scores where username = $username)
order by score desc
limit N;
要获得小于给定用户分数的M分数:
select s.*
from scores
where s.score < (select s.score from scores where username = $username)
order by score asc
limit M;
分数相同会带来一些挑战。 以下内容将上述两者与union all
元素结合在一起,并解决了此问题:
(select s.*
from scores s cross join
(select * from scores where username = $username) u
where s.score > u.score or
s.score = u.score and s.id > u.id
order by s.score desc, s.id desc
limit N
) union all
(select s.*
from scores s cross join
(select * from scores where username = $username) u
where s.score < u.score or
s.score = u.score and s.id < u.id
order by s.score, s.id
limit M
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.