I echo a rank of a student whose regd
is equal to $regd
. In fact, this is working code. However, I was advised by a friend that the MySQL statements Distinct
and Group By
should not be used together. But as a newbie, I could not figure out how I could implement it without using Distinct
because it does not return rows without Distinct
.
Can anyone suggest how I can improve this code?
<?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'];
}
}
?>
HAVING
instead ofWHERE
? Also, I think you probably intend to filter byName_of_exam
within the innermost query, rather than at the outermost query. \$\endgroup\$