这段代码:
$result = mysql_query("SELECT f_name FROM ".TBL_FACTIONS." ORDER BY f_score DESC");
$i = 1;
while($row = mysql_fetch_assoc($result))
{
echo "{$row['f_name']} & Rank: {$i}<br>";
$i++;
}
将输出:
Bla bla & Rank: 1
Foo bar & Rank: 2
Etc.
特定记录排名的 SQL 有点复杂。您可以尝试以下方法:
// E.g. rank for f_id = 123
$id = 123;
$sql = "
SELECT `a`.`rank` + `b`.`rank` AS `rank`
FROM (SELECT COUNT(*)+1 AS `rank`
FROM ".TBL_FACTIONS."
WHERE `f_score` > (SELECT `f_score`
FROM ".TBL_FACTIONS."
WHERE `f_id` = {$id})) AS `a`
STRAIGHT_JOIN (SELECT COUNT(*) AS `rank`
FROM ".TBL_FACTIONS."
WHERE `f_score` = (SELECT `f_score`
FROM ".TBL_FACTIONS."
WHERE `f_id` = {$id}) AND `f_id` < {$id}) AS `b`
";
$result = mysql_query($sql);
$row = mysql_fetch_row($result);
echo "{$id} is ranked {$row[0]}";
我在这里找到了这个查询,它是有道理的,但是如果你得到的结果是你所期望的,请彻底测试。
或者,如果您的记录集不是太大,您可以遍历结果并在找到您要查找的 ID 时跳出循环:
$id = 123;
$result = mysql_query("SELECT f_id FROM ".TBL_FACTIONS." ORDER BY f_score DESC");
$i = 1;
while($row = mysql_fetch_assoc($result))
{
if($row['f_id'] == $id)
{
echo "{$row['f_id']} is ranked {$i}<br>";
break;
}
$i++;
}