How to get rank position from @curRank

久未见 提交于 2020-12-15 05:44:54

问题


want to call up a ranking position is it posible with @curRank?

I created a rank table with

    SELECT `item`, (`totalrate` / `nrrates`) AS `rank`, @curRank := @curRank 
+ 1 AS `ranking`  FROM `rtgitems`, (SELECT 

    @curRank := 0) r WHERE item
    REGEXP 'Total'
     ORDER BY (`totalrate` / `nrrates`)  DESC

I get a table

item       rank      ranking 

Karla       9.5       1
Kelly       9.3       2
Arian       9.1429    3

in the kelly page i want to call up her ranking position

    SELECT `item`, (`totalrate` / `nrrates`) 
AS `rank`, @curRank := @curRank + 1 AS `ranking` 
FROM `rtgitems`, 
(SELECT @curRank := 0) r WHERE item REGEXP 'kelly' 
ORDER BY (`totalrate` / `nrrates`) DESC LIMIT 10
echo "<td align='center' width='250'>" . $row['ranking'] . "</td>";  

but it only gives me a 1 instead of 2


回答1:


You can move the WHERE clause out of ranking calculation results.

Example:

SELECT * FROM (
    SELECT
        `item`, (`totalrate` / `nrrates`) AS `rank`, 
        @curRank := @curRank + 1 AS `ranking` 
    FROM `rtgitems`, (SELECT @curRank := 0) r 
    ORDER BY (`totalrate` / `nrrates`) DESC 
    LIMIT 10
) results
WHERE item REGEXP 'kelly' 



回答2:


You can use any one of the solutions:

  1. You need to use a subquery to maintain rank position.

This will give you a result whose rank is 4:

SELECT * 
FROM
(
    SELECT item, (`totalrate` / `nrrates`) AS `rank`,     
    @curRank := @curRank + 1 AS ranking
    FROM rtgitems p, (SELECT @curRank := 0) r 
    ORDER BY (`totalrate` / `nrrates`) DESC
) AS stat
WHERE ranking = 2;
  1. You can even use LIMIT OFFSET to query as they are already in order:
    SELECT item, (`totalrate` / `nrrates`) AS `rank`
    FROM rtgitems
    ORDER BY (`totalrate` / `nrrates`) DESC 
    LIMIT 4, 1



来源:https://stackoverflow.com/questions/23033051/how-to-get-rank-position-from-currank

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