gpt4 book ai didi

MySQL - 围绕特定行标准选择行

转载 作者:行者123 更新时间:2023-11-29 01:59:08 24 4
gpt4 key购买 nike

我正在尝试仅选择特定行标准前后相邻的 N 行和 M 行,以获得关注用户个人得分的高分表(与具有类似得分 N 以上和 M 以下的玩家相比)。

scores-------id:intusername: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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com