使用MySQL / PHP汇总列

时间:2013-03-30 19:25:17

标签: php mysql sum

我的问题是,当我在浏览器中运行代码时,为什么HW1 / HW2 / HW3列有空值? Studentid和Sum列正确显示代码。任何理想如何解决这个问题?

<?php

$result = mysqli_query($con,"SELECT studentid,SUM(hw1+hw2+hw3) 
FROM grade
GROUP BY studentid");

echo "<table border='1'>
<tr>
<th>StudentID</th>
<th>HW1</th>
<th>HW2</th>
<th>HW3</th>
<th>SUM</th>

</tr>";

while($row = mysqli_fetch_array($result))
 {
 echo "<tr>";
 echo "<td>" . $row['studentid'] . "</td>";
 echo "<td>" . $row['hw1'] . "</td>";
 echo "<td>" . $row['hw2'] . "</td>";
 echo "<td>" . $row['hw3'] . "</td>";
 echo "<td>" . $row['SUM(hw1+hw2+hw3)'] . "</td>";

 ;}

 echo "</table>";

 mysqli_close($con);
?>

3 个答案:

答案 0 :(得分:1)

只需将您的查询更改为此

即可
"SELECT studentid,hw1, hw2, hw3, SUM(hw1+hw2+hw3) as hw
FROM grade
GROUP BY studentid"

答案 1 :(得分:0)

我不确定,因为你的问题写得不好。但我认为你只需要这样做就可以获得价值:

SELECT studentid,hw1,hw2,hw3,SUM(hw1 + hw2 + hw3)

答案 2 :(得分:0)

因为您没有选择列,请尝试:

$result = mysqli_query($con, 'SELECT `studentid`, `hw1`, `hw2`, `hw3`, SUM(`hw1`+`hw2`+`hw3`) as `sum` FROM `grade` GROUP BY `studentid`');

while($row = mysqli_fetch_array($result)) {
    echo "<tr>";
    echo "<td>" . $row['studentid'] . "</td>";
    echo "<td>" . $row['hw1'] . "</td>";
    echo "<td>" . $row['hw2'] . "</td>";
    echo "<td>" . $row['hw3'] . "</td>";
    echo "<td>" . $row['sum'] . "</td>";
}