我正在研究如何在有序的SQL记录集中获取记录的位置
这是一个在线排行榜,我已将最后提交的分数的ID设置为$ myID,所以现在我需要获得它所获得的排名。
我会像这样订购它们;
SELECT * FROM leaderboards ORDER BY score DESC
我要在声明中添加什么来获取id的特定位置
答案 0 :(得分:2)
最常见的方法是:
SET @rowcount = 0;
SELECT lb.*, (@rowcount := @rowcount + 1) as 'position'
FROM leaderboards lb ORDER BY score DESC
并且整个查询看起来像
SET @rowcount = 0;
SELECT rc.position
FROM (
SELECT lb.id, (@rowcount := @rowcount + 1) as 'position'
FROM leaderboards lb ORDER BY score DESC
) rc
WHERE rc.id = $myID
答案 1 :(得分:0)
这会产生预期的结果
SELECT count(id) FROM leaderboards where score >= (
select score from leaderbords where id = $myID
)