This question already has answers here:
How best to get someone's 'rank' from a scores table with php and mysql without looping
                                
                                    (3个答案)
                                
                        
                                5年前关闭。
            
                    
我有一个数据库,其结构类似于:

http://www.sqlfiddle.com/#!2/6c5239

当前在.php脚本中查找我所奔跑的人的等级

SELECT * FROM people ORDER BY score DESC;

并循环遍历结果,每行增加一个"rank"变量,直到我点击所需的名称,输出结果,然后中断循环。

我觉得这对于获得排名来说是一种非常低效的方式,这不仅对于Web服务器必须循环遍历数据,而且对于SQL数据库返回整个表而言都是如此。

有没有一种更简单的方法可以执行此操作,可能全部通过一条不会使SQL Server负担过多的SQL语句?

最佳答案

select * from (
    select
    p.*,
    @rank:=IF(@prev_score != score, @rank + 1, @rank) as rank,
    @prev_score := score
    from
    people p
    , (select @rank:=1, @prev_score:=null) var_init
    order by score desc
) sq where rank = 5;



看到它在sqlfiddle中实时运行


这是针对MySQL的。您的问题被标记为MySQL,但是在sqlfiddle中指定了SQL Server。

对于SQL Server,它将是这样的:

; with cte as (
select
p.*,
rank() over (order by score desc) as my_rank
from
people p
) select * from cte where my_rank = 5;


更新:

select * from (
    select
    p.*,
    @rank:=IF(@prev_score != score, @rank + 1, @rank) as rank,
    @prev_score := score
    from
    people p
    , (select @rank:=1, @prev_score:=null) var_init
    order by score desc
) sq where name = 'whatever';

10-07 12:37
查看更多