Mysql - How to get a row number after Order by?

Let's say I have a table with the following columns:


p_id

userid

points


Let's say these columns have over 5000 records. So we actually have users with points. Each user has an unique row for their point record. Imagine that every user can get points on the website by clicking somewhere. When they click I update the database with the points they get.

So we have a table with over 5000 records of people who have points, right? Now I would like to order them by their points (descending), so the user with the most point will be at the top of the page if I run a MySQL query.

I could do that by simply running a query like this:

SELECT `p_id` FROM `point_table` ORDER BY `points` DESC

This query would give me all the records in a descending order by points.

Okay, here my problem comes, now (when it is ordered) I would like to display each user which place are they actually. So I'd like to give each user something like this: "You are 623 of 5374 users". The problem is that I cannot specify that "623" number.

I would like to run a query which is order the table by points it should "search" or count the row number, where their records are and than return that value to me.

Can anyone help me how to build a query for this? It would be a really big help. Thank you.

Answers


This answer should work for you:

SET @rank=0;
SELECT @rank:=@rank+1 AS rank, p_id FROM point_table ORDER BY points DESC;

Update: You might also want to consider to calculate the rank when updating the points and saving it to an additional column in the same table. That way you can also select a single user and know his rank. It depends on your use cases what makes more sense and performs better.

Update: The final solution we worked out in the comments looked like this:

SELECT
rank, p_id
FROM
    (SELECT
     @rank:=@rank+1 AS rank, p_id, userid
     FROM
     point_table, (SELECT @rank := 0) r
     ORDER BY points DESC
    ) t
WHERE userid = intval($sessionuserid); 

Need Your Help

Cyanogen cursor access

android mouse cyanogenmod

I'm currently working on a Synergy (http://sourceforge.net/projects/synergyandroid/, synergy-foss.org) port to the android phone. I have keystrokes working -- I'm writing the key events to /dev/uin...

Resize issue in Firefox - on load?

javascript jquery firefox

I'm having a bit of an issue, I have the script below, and if works fine in Chrome, IE (partially Safari), but not in Firefox.

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.