Find the ranking of an integer in mysql [duplicate]

寵の児 提交于 2019-12-02 01:55:57

Ordered by country ASC:

SELECT 1+COUNT(*) AS ranking
FROM countryTable
WHERE country < 45 ;

Ordered by clicks DESC:

SELECT 1+COUNT(*) AS ranking
FROM countryTable AS t
  JOIN countryTable AS c
      ON c.clicks > t.clicks
WHERE t.country = 45 ;

You can get 2 rank as below it like below:

Select * from tabeName order by clicks limit 1,1

For 3 rank:

Select * from tabeName order by clicks limit 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

This will show the correct rank (2) for country 45. You don't specify how to rank ties, so you may want to change the comparison to suit you. Non existing countries rank as 0.

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

SQLfiddle here.

Itay Moav -Malimovka

X is the rank you need to look for:

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

Here's another (stunningly fast) way (albeit limited to 256 rows):

SELECT country
     , clicks
     , FIND_IN_SET(clicks,(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC) FROM country_clicks)) rank
FROM country_clicks

or, if you prefer...

SELECT FIND_IN_SET(clicks,(SELECT GROUP_CONCAT(DISTINCT clicks ORDER BY clicks DESC) FROM country_clicks)) rank
   FROM country_clicks
  WHERE country = 45;
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!