我的学生表包含字段:值
firstname : John
lastname : Doe
english-grd : 87
math-grd : 80
science-grd : 85
total-grade : 0
我的问题是我将如何仅使用“-grd”来获取字段并将其总计为总数。
答案 0 :(得分:2)
查询:
Select english-grd,math-grd,science-grd,(english-grd+math-grd+science-grd) as tot from table
答案 1 :(得分:0)
update tableName set `total-grade` = (
`english-grd` + `math-grd` + `science-grd`
)
答案 2 :(得分:0)
// this example just update one row
$student_id = 1; // example only
$res=mysql_query("SELECT * FROM Student where student_id='" . $student_id . "'");
$field_count = mysql_num_fields($res); //count field numbers
$total_grades = 0;
for ($i = 0; $i < $field_count; $i++)
{
$field_name=mysql_field_name($res, $i);
if (substr($field_name,-4) == '-grd')
{
$total_grades = $total_grades + mysql_result($res,0,$i); // 0 refer to first row ...there is only one row from $res...$i is offset of the column
}
}
mysql_query("update Student SET total-grade='" . $total_grades . "' where student_id='" . $student_id . "'");