SQL query performance improvement for advice

巧了我就是萌 提交于 2019-12-06 08:47:52

User defined variables are probably faster than what you are doing. However, you need to be careful when using them. In particular, you cannot assign a variable in one expression and use it in another -- I mean, you can, but the expressions can be evaluated in any order so your code may not do what you intend.

So, you need to do all the work in a single expression:

select s.*,
       (@rn := if(@s = score, @rn,
                  if(@s := score, @rn + 1, @rn + 1)
                 )
       ) as rank
from scores s cross join
     (select @rn := 0, @s := 0) params
order by score desc;

One option is to use user-defined variables:

select score, 
       @rnk:=if(@prevScore=score,@rnk,@rnk+1) rnk,
       @prevScore:=score
from scores
     join (select @rnk:=0, @prevScore:=0) t
order by score desc
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!