Sql排名查询

时间:2017-12-04 04:44:50

标签: mysql sql database

我有一个从MySQL update statement to list ranking positions找到的排名查询,但我有另一个要求,在找到排名之后我需要列出给定的player_id的排名以及给定player_id的上下几个玩家。

是否可以在单个查询中执行此操作?

示例数据:

rank player_id score
"1" "801"   "4995599"
"2" "800"   "4995599"
"3" "789"   "4995439"
"4" "1528"  "4993900"
"5" "1150"  "4993700"
"6" "2269"  "4993611"
"7" "465"   "4993523"

期望的输出: player_id = 1528

rank player_id score
"2" "800"   "4995599"
"3" "789"   "4995439"
"4" "1528"  "4993900"
"5" "1150"  "4993700"
"6" "2269"  "4993611"

编辑1: 样本代码:

SET @rank = 1, @seq = 1, @last = null;

select * from (
select *, @myRank := rank from (
SELECT *, @rank := if(@last = score, @rank, @seq) AS rank, @seq := @seq + 1, 
@last := score FROM score ORDER BY score DESC) as d where player_id = 789) 
as f where rank between @myRank -2 and @myRank + 2 ;

的问候, KUMAR KS。

1 个答案:

答案 0 :(得分:1)

你是说这个

吗?
SET @r=0;
select * from (select @rownum:=@rownum+1 ‘rank’, p.* 
from player p,(SELECT @rownum:=0) r order by score desc) where rank>=@r-2 and rank<=@+2;

或者,我确定它的性能不会降低

    SET @play_id = 0;
    set @above=2;
    set @below=2
    SELECT
        *
    FROM
        (
            SELECT
                @rownum :=@rownum + 1 rank,
                p.*
            FROM
                player p,
                (SELECT @rownum := 0) r
            ORDER BY
                score DESC
    ) t
WHERE
    rank >=(select rank from (
        SELECT
            @rownum :=@rownum + 1 ‘rank’,
            p.*
        FROM
            player p,
            (SELECT @rownum := 0) r
        ORDER BY
            score DESC
    ) a where play_id=@play_id) - @above
AND rank <=(select rank from (
        SELECT
            @rownum :=@rownum + 1 ‘rank’,
            p.*
        FROM
            player p,
            (SELECT @rownum := 0) r
        ORDER BY
            score DESC
    ) a where play_id=@play_id) + @above;