Jump to content

[SOLVED] Get rank by high score


jstngk

Recommended Posts

I have a very large table with a single row for each user that holds a game score. For example the table is structure is like this (simplified for example):

 

|id|username|score|

 

|0|bob|556221

|1|Samantha|232

|2|levi|54645

 

What I want to do is just select a single row such as with:

 

"SELECT `score` FROM `highscore` WHERE `username` = 'bob' LIMIT 1"

 

However I want to know what rank they are by score. So for example I want to use the SELECT statement above to get bob’s score but I also want to know he is ranked #23 by the score field. It would be easy if we were only talking a few rows, as you could just pull the entire table and loop through it real quick, but I am talking thousands and thousands of rows and growing. What would be the most effective way to do this? Thank you ahead of time I am new to phpfreaks.

 

Link to comment
Share on other sites

Hi

 

Possibly more elegant way of doing it (excuse any typos), but I suspect fair inefficient.

 

SELECT z.*, x.Rank
FROM `highscore` z
INNER JOIN (SELECT a.username, a.score, @num := @num + 1 AS Rank from `highscore` a, (SELECT @num := 0) d
order by a.score) x
ON z.username = x.username
WHERE z.username = 'bob' 
LIMIT 1

 

All the best

 

Keith

Link to comment
Share on other sites

  • 1 month later...

Hi

 

Possibly more elegant way of doing it (excuse any typos), but I suspect fair inefficient.

 

SELECT z.*, x.Rank
FROM `highscore` z
INNER JOIN (SELECT a.username, a.score, @num := @num + 1 AS Rank from `highscore` a, (SELECT @num := 0) d
order by a.score) x
ON z.username = x.username
WHERE z.username = 'bob' 
LIMIT 1

 

All the best

 

Keith

Sorry it took so long for me to get back, this is awesome THANK YOU so much ++
Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.