繁体   English   中英

如何使用 WHERE 子句使用表本身和 MySQL 中的另一个表的值总和来更新表

[英]How to update a table with sum of values from the table itself and another table in MySQL with WHERE clause

我知道有类似的问题,但答案并不完全是我一直在寻找的。 我有两个 MySQL 表,我会说table1table2 table1中的字段是StudentIDGradeTotal_Score 并且table2中的字段也是StudentIDGradeTotal_Score 我想要做的是 SUM(table1.Total_Score) 并将其添加到 SUM(table2.Total_Score)。 因此table2中的Total_Scoretable1中的分数一起累加。 总分 我试图用下面的代码来实现这一点,但是table2中的分数。 Total_Score永远不会累积。 即使我的代码没有出错,它们也保持不变。 请参阅下面的代码。

update table2 o inner join
(
SELECT op.StudentID,
sum(ot.Total_Score) as Total_Score_ot
 sum(op.Total_Score) as Total_Score_op
FROM table1 ot inner join table2 op on op.StudentID = ot.StudentID
WHERE ot.Grade = 'Grade8'
GROUP BY op.StudentID
) as o1 on o.StudentID = o1.StudentID
SET Total_Score=Total_Score_op + Total_Score_ot

嗯。 . . 我认为您不需要在子查询中加入:

update table2 o inner join
       (select ot.StudentID, sum(ot.Total_Score) as Total_Score_ot
        from table1 ot
        where ot.Grade = 'Grade8'
        group by ot.StudentId
       ) ot
       using (studentid)
    set o.Total_Score = o.Total_Score + Total_Score_ot;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM