在mysql中找到整数的排名

时间:2013-01-12 14:59:39

标签: php mysql sql ranking

  

可能重复:
  Mysql rank function

我有以下countryTable

country  clicks
-------  ------
0        222
66       34 
175      1000
45       650

如何获得说国45的排名,在这种情况下为2?

6 个答案:

答案 0 :(得分: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 ;

答案 1 :(得分:2)

你可以获得如下所示的2级排名:

Select * from tabeName order by clicks limit 1,1

3级:

Select * from tabeName order by clicks limit 2,1

答案 2 :(得分:1)

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

答案 3 :(得分:1)

这将显示国家/地区45的正确等级(2)。您没有指定如何对关系进行排名,因此您可能希望更改比较以适合您。不存在的国家排名为0.

SELECT COUNT(*) rank 
FROM countryTable a
JOIN countryTable b
  ON a.clicks <= b.clicks
WHERE a.country = 45

SQLfiddle here

答案 4 :(得分:0)

X是您需要查找的排名:

SELECT * FROM T ORDER BY clicks DESC LIMIT X-1,1

答案 5 :(得分:0)

这是另一种(惊人的快速)方式(尽管限制为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;