从表一张表中选择数据,然后插入另一个表中



我有两个表;resulttotal

result(student_code,mark)
total(student_code,total)

total列应包含学生的总数。

因此,我已经写了一个SQL语句,通过使用Select语句将数据从结果表中插入总表中,该语句应将特定的student_code及其标记作为求和,然后将其存储在total表中。

但是,每当我尝试时,查询要么失败,要么只吸用一个学生

当我使用此查询时,它有效,但仅适用于一个student_code是1的学生,但我需要将所有学生及其标记作为总计

<?php
// copy student student_code and summation of his/her mark  from result table into total table
$query = 'INSERT INTO total
(student_code, total)
SELECT  student_code, SUM(mark)
FROM
result
WHERE
student_code = 1';
$sql = mysql_query($query) or (mysql_error());
?>

当我使用学生代码作为变量时,我一无所获

<?php
// copy student student_code and summation of his/her mark  from result table into total table
$query = 'INSERT INTO total
(student_code, total)
SELECT  student_code, SUM(mark)
FROM
result
WHERE
student_code = "' . $student_code . '"';
$sql = mysql_query($query) or (mysql_error());
?>

您必须执行两个不同的查询第一个查询选择数据,然后将其存储到PHP变量中,然后使用第二个查询

将其插入另一个表中

更新----

尝试此代码

<?php
for($i = 1; $i < 102; $i++)
{
$query = 'INSERT INTO total (student_code, total) SELECT  student_code, SUM(mark) FROM result WHERE student_code = "$i"';
$sql = mysql_query($query) or (mysql_error());
}
?>

它必须工作

最新更新