Use of AVG function in MySQL
I want to know the top 3 student in my database so I use AVG function but it seems I have some errors this is my code:
$result = mysql_query("SELECT grade.GStudNo, AVG(grade.Grade) as Grade, students.LName, students.FName, students.MName, stu开发者_JS百科dents.Course
FROM students INNER JOIN grade ON students.StudNo = grade.GStudNo
WHERE GSem = '1st Semester' AND GYear = '2007'
GROUP BY grade.GStudNo
ORDER BY AVG(grade.Grade) ASC")
...
<?php while($myrow = mysql_fetch_assoc($result))
{?>
<tr>
<td><?php echo "$myrow[LName] ";echo "$myrow[FName] "; echo "$myrow[MName]"; ?></td>
<td><?php echo "$myrow[Grade]";?></td>
</tr>
<?php } ?>
this is the error message : Notice: Undefined index: Grade in C:\xampp\htdocs\strawman\default.php on line 368
but i defined the AVG(grade.Grade)AS Grade.. :(
MySQL might be confused as you are using the field name Grade
as alias and use it afterwards in AVG in your ORDER clause again. Try this one (it calls AVG only once):
SELECT grade.GStudNo, AVG(grade.Grade) as gradeAverage ...
ORDER BY gradeAverage ASC
And, why are you using double quotes around the variables? That'll be much quicker to process:
<?php echo $myrow['LName'] .' '. $myrow['FName'] .' '. $myrow['MName']; ?>
You're using the following syntax:
<?php echo "$myrow[LName] ";
You'll want to use something like this:
<?php echo "$myrow['LName'] ";
Or, my preferred syntax when using double quotes:
<?php echo "{$myrow['LName']} ";
And the same goes for the other variables.
Leaving out the quotes will cause PHP to 'guess' what you mean. It'll go fine sometimes, horribly wrong other times.
精彩评论