如何改进这个php mysql代码?

时间:2013-07-25 13:20:19

标签: php mysql

使用这些代码,我会回复Rank等于regd的学生$regd。实际上,这是一个有效的代码。但是,朋友告诉我,在mysql语句DistinctGroup By中不应该一起使用。但作为一个新手,我无法弄清楚如何在不使用Distinct的情况下实现它,因为它不返回没有Distinct的行。谁能建议我如何改进这些代码?

<?php 
mysql_select_db($database_dbconnect, $dbconnect);
$query_myrank = "SELECT Distinct regd, Name_of_exam, 
                        Name_of_Student, TOTALSCORE, Rank 
                 FROM (SELECT *, IF(@marks = (@marks := TOTALSCORE), 
                              @auto, @auto := @auto + 1) AS Rank 
                       FROM (SELECT Name_of_Student, regd, 
                                   Name_of_exam, SUM(Mark_score) AS TOTALSCORE 
                             FROM cixexam, (SELECT @auto := 0, 
                                                   @marks := 0) AS init 
                                            GROUP BY regd 
                             ORDER BY TOTALSCORE DESC) t) AS result 
                 HAVING (Name_of_exam='First Terminal Exam' OR 
                         Name_of_exam='First Term Test')";

$myrank = mysql_query($query_myrank, $dbconnect) or die(mysql_error());

$i = 0;
$j = 0;
$data = array();
while($row_myrank = mysql_fetch_assoc($myrank))
{
    $data[$i] = $row_myrank;
    if(isset($data[$i - 1]) 
           && $data[$i - 1]['TOTALSCORE'] == $data[$i]['TOTALSCORE'])
    {
       $data[$i]['Rank'] = $j;
    }else{
       $data[$i]['Rank'] = ++$j;
    }
       $i++;
}
foreach($data as $key => $value)
{
    if($value['regd'] == $regd)
    {
        echo $value['Rank'];
    }
}
?>    

2 个答案:

答案 0 :(得分:1)

DistinctGroup By慢。你可以在不使用Group ByDistinct的情况下这样做,这可能是你想要实现的目标。

SELECT regd, Roll_no, Name_of_Student, Name_of_exam,
       TOTALSCORE, Rank 
FROM 
(
  SELECT t.*, IF(@p = TOTALSCORE, @n, @n := @n + 1) AS Rank, @p := TOTALSCORE 
    FROM
  (
    SELECT regd, Roll_no, Name_of_Student, Name_of_exam, 
            SUM(Mark_score) TOTALSCORE
    FROM cixexam, (SELECT @n := 0, @p := 0) n 
     WHERE (Name_of_exam='First Terminal Exam' OR Name_of_exam='First Term Test')
     GROUP BY regd 
     ORDER BY TOTALSCORE DESC
  ) t
) r

答案 1 :(得分:0)

从这开始:

请不要将mysql_ *函数用于新代码。它们是no longer maintained,社区已经开始the deprecation process

相反,您应该了解准备好的语句并使用PDOMySQLi。如果您无法决定,请撰写本文will help to choose

如果您想学习here is good PDO tutorial