MySQL get row position in ORDER BY

前端 未结 9 1248
囚心锁ツ
囚心锁ツ 2020-11-22 13:57

With the following MySQL table:

+-----------------------------+
+ id INT UNSIGNED             +
+ name VARCHAR(100)           +
+----------------------------         


        
9条回答
  •  忘掉有多难
    2020-11-22 14:45

    The other answers seem too complicated for me.

    Here comes an easy example, let's say you have a table with columns:

    userid | points
    

    and you want to sort the userids by points and get the row position (the "ranking" of the user), then you use:

    SET @row_number = 0;
    
    SELECT 
        (@row_number:=@row_number + 1) AS num, userid, points
    FROM
        ourtable
    ORDER BY points DESC
    

    num gives you the row postion (ranking).

    If you have MySQL 8.0+ then you might want to use ROW_NUMBER()

提交回复
热议问题