我试图在某个行标准之前和之后仅选择相邻的N和M行,用于关注用户个人得分的高分表(与具有类似得分N以上和M以下的玩家相比)。
scores ------- id:int username:varchar(120) score:int
注意:每个用户名都有多个分数。高分数据库只是一个分数转储
因此,仅获取前十名全球分数:SELECT max(score),username FROM scores GROUP BY username, ORDER BY score DESC
但是,我正试图为任意用户做这件事 - 大多数用户都没有幸运地进入前10名......
如何在某个用户的分数上方引用N行和M行,以便在用户得分之上和之下提取10个分数?
答案 0 :(得分:3)
要获得高于用户的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
)