向用户显示根据分数排序后的位置


show users the position after sorting based on score

我有一个表,它有id列和score列,我想根据score列对表进行排序,然后找到加载页面的特定用户,并向他/她的位置显示。例如,告诉他"你的职位是第40位"。我知道如何对查询进行排序:

SELECT id,score FROM `table` ORDER BY `score` DESC

但排序后,我如何才能找到特定id的位置?

您不需要order by。相反:

select 1 + count(*)
from table t
where t.score > (select t2.score from table t2 where id = $id);

试试看:

SELECT @rownum:=@rownum+1 ‘rank’, id, score FROM table t, (SELECT @rownum:=0) r ORDER BY score DESC;

这将创建一列,并在每条记录中增加1。