2012-10-31 44 views
-1

我有学生表包含字段:值获取表中的字段和值

firstname : John 
lastname : Doe 
english-grd : 87 
math-grd : 80 
science-grd : 85 
total-grade : 0 

我的问题是我会如何获取只能用“-GRD”的领域,总结有总。

回答

2

查询:

Select english-grd,math-grd,science-grd,(english-grd+math-grd+science-grd) as tot from table 
+0

如果我加入像pe_grd另一个问题,我不想重写我的代码?我认为这种方法是行不通的。 – arjay0601

+2

@ arjay0601 - 你说什么是不可能的,甚至似乎不存在,因为如果你添加或删除表中的列,那么你正在修改该表的内部结构,这确实不独立于其余的环境。 – Lion

+0

你打算使用PHP吗? –

0
update tableName set `total-grade` = (
`english-grd` + `math-grd` + `science-grd` 
) 
+0

如果我添加了另一个像pe_grd这样的主题,并且想在重写代码时将其与它相加,该怎么办? – arjay0601

+0

http://stackoverflow.com/questions/1448192/can-a-mysql-select-statement-work-without-specifying-column-names –

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 . "'"); 
+0

对于多行,你应该使用'$ table_rows = mysql_num_rows($ res );'并使用另一个循环...我希望它能起作用! –