I have a MySQL table that looks like this:
id (int primary)
name (text)
rating (float)
I have a page showing rankings which looks like this:
$i = 0;
$q = mysql_query("SELECT * FROM teams ORDER BY rating DESC");
while($r = mysql_fetch_assoc($q)){
$i++;
print("$i: {$r['name']}<br>");
}
This shows teams in order of their rating, with a ranking. And it works.
Now, if I’m given the ID of a team, how do I find their ranking without running through the loop like this? A single MySQL query which returns the team’s info + a numeric ranking indicating how far down the list they would be, if I had rendered the whole list.
Thanks!
To get the ranking you can do:
To get all the relevant info too, you can do:
This joins
teamsto itself joining ont.rating <= t2.rating, and so you get one row for every team that has a rating higher than or equal you.The
COUNTjust counts how many teams have a rating higher than or equal to you.Note that if there’s a tie this will give you the lower rank. You can change the
<=to a<if you want the highest.