简体   繁体   中英

Get a rank, based on score, from an unordered MySql Database when given a Username

Okay so I have a table that has the following

KEY   username   password   score  

The above columns are not in any specific order.

I want to send my Database a username and have it send me back what rank that user name is based on its score. So for example if I had 10 people in there and the 3rd person in has the highest score. When I pass the 3rd persons username in I want it to send back 1.

Is this possible?

I have been trying things like this

$result = mysql_query("SELECT * FROM tablename where username='$username' ORDER BY score DESC");

but it doesnt seem to give me the row number

This will handle ranks that have the same score.

SELECT  d.*, c.ranks
FROM
        (
          SELECT    Score, @rank:=@rank+1 Ranks
          FROM
                  (
                      SELECT  DISTINCT Score 
                      FROM    tableName a
                      ORDER   BY score DESC
                  ) t, (SELECT @rank:= 0) r
        ) c 
        INNER JOIN tableName d
            ON c.score = d.score
// WHERE   d.username = 'Helen'

for example

KEY     username    password    score   Ranks
1       Anna        123         5       3
2       Bobby       345         6       2
3       Helen       678         6       2
4       Jon         567         2       4
5       Arthur      ddd         8       1

for better performance, add an INDEX on column Score ,

ALTER TABLE tableName ADD INDEX (Score)
SELECT 
    (SELECT COUNT(*)+1 FROM tablename WHERE score > t.score) as rank,
    * 
FROM
     tablename t
where 
     username='$username'

The ORDER BY in your query is useless since you're only returning one row.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM