-
應用場景:在對成績或者積分排名時,往往需要顯示排名;
-
成績排名:相同分數的人,名次相同
Select s.Score, case when @rowtotal = s.Score then cast(@rownum as SIGNED INTEGER) # 當這個成績和@rowtotal上一次的成績相同時,@rownum不變 when @rowtotal := s.Score then cast(@rownum :=@rownum +1 as SIGNED INTEGER) # 當取到的成績和上一次成績不同時, @rownum +1 ,rank排名加一 when @rowtotal = 0 then cast(@rownum :=@rownum +1 as SIGNED INTEGER) # 當取到的成績為0時,排名+1 end as Rank from (select Id,Score from Scores order by Score desc)s, # 通過分數倒序排列成績 (Select @rownum :=0,@rowtotal :=null) r #這個是關鍵,@rownum,@rowtotal先置空,然后和上邊的成績關聯
-
積分排名:按積分插入時間排名
SELECT obj.score,@rownum := @rownum + 1 AS Rank FROM ( SELECT user_id, score FROM `sql_rank` ORDER BY score DESC, update_time ASC ) AS obj, (SELECT @rownum := 0) r
我遇到的問題是,排名顯示的是1.0,2.0的double類型,所以我用cast(@rownum as SIGNED INTEGER)轉化了一下
-