可能重复:
Mysql rank 函数
我有以下国家表
country clicks
------- ------
0 222
66 34
175 1000
45 650
在这种情况下,我如何获得国家 45 的排名,即 2?
可能重复:
Mysql rank 函数
我有以下国家表
country clicks
------- ------
0 222
66 34
175 1000
45 650
在这种情况下,我如何获得国家 45 的排名,即 2?
订购者country ASC
:
SELECT 1+COUNT(*) AS ranking
FROM countryTable
WHERE country < 45 ;
订购者clicks DESC
:
SELECT 1+COUNT(*) AS ranking
FROM countryTable AS t
JOIN countryTable AS c
ON c.clicks > t.clicks
WHERE t.country = 45 ;
您可以获得 2 等级,如下所示:
Select * from tabeName order by clicks limit 1,1
3级:
Select * from tabeName order by clicks limit 2,1
这将显示国家 45 的正确排名 (2)。您没有指定如何对平局进行排名,因此您可能需要更改比较以适合您。不存在的国家排名为 0。
SELECT COUNT(*) rank
FROM countryTable a
JOIN countryTable b
ON a.clicks <= b.clicks
WHERE a.country = 45
SELECT *
FROM
(
SELECT @ranking:= @ranking + 1 rank,
a.country,
a.clicks
FROM tableName a, (SELECT @ranking := 0) b
ORDER BY a.clicks DESC
) s
WHERE country = 45
X
是您需要寻找的等级:
SELECT * FROM T ORDER BY clicks DESC LIMIT X-1,1
这是另一种(惊人的快速)方式(尽管限制为 256 行):
SELECT country
, clicks
, FIND_IN_SET(clicks,(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC) FROM country_clicks)) rank
FROM country_clicks
或者,如果您愿意...
SELECT FIND_IN_SET(clicks,(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC) FROM country_clicks)) rank
FROM country_clicks
WHERE country = 45;