Mysql排名位置

时间:2012-01-24 13:22:17

标签: php mysql rank

数据库:

id  first_name  points
1   Bob          12
2   Jane             50
3   Jack             2
4   Bill             10
5   Nick             62
6   Kathy            18
7   Steve            42
8   Anne             52

脚本:

<?php
$con = mysql_connect("localhost","root","lol");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("st", $con);

$result = mysql_query("SELECT first_name,points,
          @curRank := @curRank + 1 AS rank
FROM      person p, (SELECT @curRank := 0) r
ORDER BY points DESC");

while($row = mysql_fetch_array($result))
  {
  echo $row['first_name'] . "  " . $row['points'];
  echo "<br />";
  }

mysql_close($con);
?>

我得到了什么;

Nick 62
Anne 52
Jane 50
Steve 42
Kathy 18
Bob 12
Bill 10
Jack 2

现在我需要添加到用户位置排名(类似于顶级功能) 例如:

Nick 62  Top 1
Anne 52  Top 2
Jane 50  Top 3
Steve 42 Top 4 and so on.....
Kathy 18
Bob 12
Bill 10
Jack 2

5 个答案:

答案 0 :(得分:1)

$position = 1;
while($row = mysql_fetch_array($result))
  {
  echo $row['first_name'] . "  " . $row['points'] . "  Top ".$position;
  echo "<br />";
  $position++;
  }

答案 1 :(得分:1)

在您的查询中,我在MySQL中使用TOP函数添加了CONCAT字。 试试这个:

SELECT   first_name,
         points,
         CONCAT('TOP ',@curRank := @curRank + 1) AS rank
FROM     person p, (SELECT @curRank := 0) r
ORDER BY points DESC"

答案 2 :(得分:0)

<?php
$con = mysql_connect("localhost","root","lol");
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db("st", $con);

$result = mysql_query("SELECT first_name,points FROM person ORDER BY points DESC");

$rank=1;
while($row = mysql_fetch_array($result))
  {
  echo $row['first_name'] . " " . $row['points'] . " Top " . $rank++;
  echo "<br />";
  }

mysql_close($con);
?>

答案 3 :(得分:0)

您应该考虑实际提取和打印排名:

echo $row['first_name'] . "  " . $row['points']. " Top {$row['rank']}";

答案 4 :(得分:-1)

  $top = 1;
  while($row = mysql_fetch_array($result))
   {
      echo $row['first_name'] . "  " . $row['points']." TOP ".$top ;
     echo "<br />";

     $top++;
   }