使用while循环对PHP MYSQL进行排名

时间:2015-10-11 15:56:10

标签: php mysql

我有问题。我根据申请人的考试成绩制作排名系统。这是代码:

$testScore = "SELECT Overall_Score, First_Name
                      FROM applicant_details, person, person_details
                      where person.ID_No like person_details.ID_No and Position_Applied = 'Work137' and Person_Type = 'Applicant' and applicant_details.ID_No like person.ID_No";

$result = mysql_query($testScore);

$rank = 0;
$lastScore = false;
$rows = 0;

while( $row = mysql_fetch_array( $result ) ){               

       $name = $row['First_Name'];
       $overall = $row['Overall_Score'];
       $rows++;

       if( $lastScore != $overall){
           $lastScore = $overall;
           $rank = $rows;
        }
        echo"Name:$name rank:$rank score: $overall </br>";
}

此代码的输出是第一个要查询的人是数字1.示例输出:

姓名:Utaha等级:1分:85

姓名:Rikka等级:2分:90

我想要一个输出:

姓名:Utaha等级:2分:85

姓名:Rikka排名1得分:90

2 个答案:

答案 0 :(得分:1)

只需使用ORDER BY [列名进行排序] [DESC / ASC]按值排序......

SELECT Overall_Score, First_Name
                  FROM applicant_details, person, person_details
                  where person.ID_No like person_details.ID_No and Position_Applied = 'Work137' and Person_Type = 'Applicant' and applicant_details.ID_No like person.ID_No ORDER BY Overall_Score DESC

如果你想保留订单,那么应该使用mysql_num_rows()来获得答案总数,并使用该数字对它们进行排名:

$rows = mysql_num_rows($result);
while( $row = mysql_fetch_array( $result ) ){               

   $name = $row['First_Name'];
   $overall = $row['Overall_Score'];

   if( $lastScore != $overall){
       $lastScore = $overall;
       $rank = $rows;
    }
    echo"Name:$name rank:$rank score: $overall </br>";
   $rows--;

}

答案 1 :(得分:0)

您的查询中需要ORDER BY子句:

$testScore = "SELECT Overall_Score, First_Name
              FROM applicant_details, person, person_details
              WHERE person.ID_No like person_details.ID_No
              AND Position_Applied = 'Work137'
              AND Person_Type = 'Applicant'
              AND applicant_details.ID_No like person.ID_No
              ORDER BY Overall_Score DESC
";

正如Gordon Linoff所暗示的那样,您可以使用正确的JOIN语法来改进此查询:

$testScore = "SELECT Overall_Score, First_Name
              FROM applicant_details
              JOIN person ON applicant_details.ID_No like person.ID_No
              JOIN person_details ON person.ID_No like person_details.ID_No
              WHERE Position_Applied = 'Work137'
              AND Person_Type = 'Applicant'
              ORDER BY Overall_Score DESC
";