[MySQL] [5] ranking function

Preface:

Rank demand often encounter: not tied rankings, tied for the query specified user rankings

@rownum: = @rownum + 1: wherein: = is assigned the role of this means is to perform @rownum + 1, then assign the value @rownum

(SELECT @rownum: = 0) r: this means rownum field is set initial value of 0

text:

Not tied rankings:

Method 1: First sort, then the results are numbered

SELECT t.*, @rownum := @rownum + 1 AS rownum 
  FROM (SELECT @rownum := 0) r, (SELECT * FROM testsort ORDER BY score DESC) t;

Method 2: first results, reorder number

SELECT t.*, @rownum := @rownum + 1 AS rownum
  FROM (SELECT @rownum := 0) r, testsort t
 ORDER BY t.score DESC;

The result is the same

Tied for:

SELECT obj.uid, obj.score,
       CASE WHEN @rowtotal = obj.score THEN @rownum  
       WHEN @rowtotal := obj.score THEN @rownum :=@rownum + 1  
       WHEN @rowtotal = 0 THEN @rownum :=@rownum + 1 
        END AS rownum
  FROM ( SELECT uid, score FROM testsort ORDER BY score DESC ) obj,  
       (SELECT @rownum := 0 ,@rowtotal := NULL) r

Specifies the user query ranking:

SELECT b.* FROM  
( 
    SELECT t.*, @rownum := @rownum + 1 AS rownum 
      FROM (SELECT @rownum := 0) r, (SELECT * FROM testsort ORDER BY score DESC) t;
 ) AS b WHERE b.uid = x;

Reference blog:

MYSQL achieve the specified user query and ranking ranking function (tied for function) script code examples _Mysql_ House
https://www.jb51.net/article/148757.htm

Mysql three methods to achieve a ranking function of - CSDN blog - mingqing6364
https://blog.csdn.net/mingqing6364/article/details/82621840

Guess you like

Origin www.cnblogs.com/huashengweilong/p/11365558.html