Mysql Sort Get Ranking Instance Code

  • 2021-10-25 08:07:00
  • OfStack

The code looks like this:


SELECT @i:=@i+1 rowNum,
if(@total=t.s_score,@rank,@rank:=@i) rank,@total:=t.s_score,
t.*
from(
select t1.* ,t2.s_score from student t1 LEFT JOIN score t2 on t1.s_id=t2.s_id and t2.c_id="01" ORDER BY t2.s_score desc
)t,(select @i:=0,@rank:=0,@total:=null) s ;
SELECT @i:=@i+1 rowNum,
if(@total=t.s_score,@rank,@rank:=@rank+1) rank,@total:=t.s_score,
t.*
from(
select t1.* ,t2.s_score from student t1 LEFT JOIN score t2 on t1.s_id=t2.s_id and t2.c_id="01" ORDER BY t2.s_score desc
)t,(select @i:=0,@rank:=0,@total:=null) s ; 

Mysql gets the ranking after the results are sorted

In fact, it is the sorted line number of the output mysql

RT: Get the ranking of a single user's score among all users' scores

It can be divided into two steps:

1. Find out all users and their performance rankings


select id,maxScore,(@rowNum:=@rowNum+1) as rowNo 
from t_user, 
(select (@rowNum :=0) ) b 
order by t_user.maxScore desc  

2. Find out the ranking of a user in all user scores


select u.rowNo from ( 
select id,(@rowNum:=@rowNum+1) as rowNo 
from t_user, 
(select (@rowNum :=0) ) b 
order by t_user.maxScore desc ) u where u.id="2015091810371700001"; 

Summarize


Related articles: