Reputation: 237
I'm looking at how I can get the position of a record in an ordered SQL recordset
It's an online leaderboard, I've set the id of the last submitted score to $myID, so now I need to get what ranking it got.
I'll be ordering them like so;
SELECT * FROM leaderboards ORDER BY score DESC
What do I add to the statement to just get a specific position of an id
Upvotes: 0
Views: 242
Reputation: 12587
Most common approach is:
SET @rowcount = 0;
SELECT lb.*, (@rowcount := @rowcount + 1) as 'position'
FROM leaderboards lb ORDER BY score DESC
and whole query would look like
SET @rowcount = 0;
SELECT rc.position
FROM (
SELECT lb.id, (@rowcount := @rowcount + 1) as 'position'
FROM leaderboards lb ORDER BY score DESC
) rc
WHERE rc.id = $myID
Upvotes: 2
Reputation: 19915
This would give the desired result
SELECT count(id) FROM leaderboards where score >= (
select score from leaderbords where id = $myID
)
Upvotes: 0