[英]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.
例如,如果我在那里有10个人,那么第3个人的得分最高。 When I pass the 3rd persons username in I want it to send back 1.
当我通过第三人的用户名时,我希望它发回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
, 为了获得更好的性能,请在列
Score
上添加INDEX
,
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. 查询中的
ORDER BY
是无用的,因为您只返回一行。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.