我有一个排名系统,当我传递player_ID时,它将在我的player_id上方和下方返回2个值。但问题是如果上面或下面的玩家排名是相同的,它会返回所有值,但我需要五个值。
我的代码:
SET @rank = 1, @seq = 1, @last = null;
select ranks.rank , ranks.id, ranks.scores from (
SELECT *, @rank := if(@last = scores, @rank, @seq) AS rank, @seq := @seq + 1, @last := scores FROM testingleaderboard ORDER BY scores DESC) as ranks JOIN (
-- find the rank of the user we want similarly
SELECT @sd:=COUNT(id) rank
FROM testingleaderboard JOIN (
-- our user's highest score
SELECT MAX(scores) maxscore FROM testingleaderboard WHERE id = 46818
) userscore ON testingleaderboard.scores > userscore.maxscore
-- filter for only those who are within given range from our user's rank
) userrank ON ranks.rank BETWEEN userrank.rank - 2 AND userrank.rank + 3
-- sort the results
ORDER BY ranks.rank
INPUT:
id = 46818
收到的输出:
"rank" "id" "scores"
"426688" "1032909" "6138"
"426688" "1094298" "6138"
"426688" "1081638" "6138"
"426688" "1016393" "6138"
"426688" "1016503" "6138"
"426688" "1020950" "6138"
"426688" "39479" "6138"
**"426688" "46818" "6138"**
"426688" "29181" "6138"
"426688" "31458" "6138"
"426688" "33779" "6138"
"426688" "23640" "6138"
"426688" "4852" "6138"
必需的输出:
"426688" "1020950" "6138"
"426688" "39479" "6138"
**"426688" "46818" "6138"**
"426688" "29181" "6138"
"426688" "31458" "6138"
答案 0 :(得分:0)
这是你想要的吗?
(select tlb.*
from testingleaderboard tlb
where tlb.score <= (select tlb2.score from testingleaderboard tlb2 where tlb2.id = @id)
order by (tlb.id = @id) desc, score desc
limit 3
) union all
(select tlb.*
from testingleaderboard tlb
where tlb.score > (select tlb2.score from testingleaderboard tlb2 where tlb2.id = @id)
order by score asc
limit 2
);
这将返回两个分数较小或相等的行,具有id的行和两个分数较大的行。在某些情况下,这可能会错过具有相同分数的行。弄清楚如何处理这种情况可能很棘手。
答案 1 :(得分:-1)
只需在查询结尾添加限制5。
query limit 5;
e.g。 选择*从任何地方订购某些限制5;