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

假如想象 提交于 2019-12-05 01:34:25

问题


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


回答1:


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'
  • SQLFiddle Demo (Ranking with duplicates)
  • SQLFiddle Demo (with filtering)

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)



回答2:


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.



来源:https://stackoverflow.com/questions/15137093/get-a-rank-based-on-score-from-an-unordered-mysql-database-when-given-a-userna

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