我试图仅选择特定行标准之前和之后的相邻 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
)
关于MySQL-围绕特定行条件选择行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19717954/