Possible Duplicate:
Mysql rank function
I have the following countryTable
country  clicks
-------  ------
0        222
66       34 
175      1000
45       650
How do I get the ranking of say country 45 which is 2 in this case?
Possible Duplicate:
Mysql rank function
I have the following countryTable
country  clicks
-------  ------
0        222
66       34 
175      1000
45       650
How do I get the ranking of say country 45 which is 2 in this case?
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
 
    
    X is the rank you need to look for:
SELECT * FROM T ORDER BY clicks DESC LIMIT X-1,1
 
    
     
    
    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;
 
    
    