要获得高于用户的 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;
拥有相同的分数会带来一些挑战。下面将上述两者与 a 结合起来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
)