MYSQL 5.7 Getting the row number

瘦欲@ 提交于 2021-02-10 23:16:31

问题


I have a database called "playerrank" that has points column. I want to show on people's profile page their rank like this:

Rank: 3/1456

I tried using ROW_NUMBER() but it seems like my host has low version (5.7 i believe).its giving me errors.

Is there another way i can get the ranking of a player based on points other than ordering the db by points desc and getting the row number somehow?


回答1:


One option to simulate row number in MySQL 5.7 uses session variables:

SET @row_number = 0;

SELECT 
    (@row_number:=@row_number + 1) AS rnk, points
FROM yourTable
ORDER BY points DESC;

Note that technically row number is not the same thing as rank, but I suspect that you do want row number here. In this case, if say three players were tied with the same number of points, they might have a different rank number assigned to them.




回答2:


In MySQL 5.7, in a single query

SELECT 
    (@row_number := @row_number + 1) AS rnk, points
FROM yourTable,
(SELECT @row_number := 0) AS x
ORDER BY points DESC;


来源:https://stackoverflow.com/questions/54239851/mysql-5-7-getting-the-row-number

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!