I'm trying to update table yy from table xx results by doing sum.
For example (syntax is abstract):
update table_yy
set sum_of_x_and_y = (
(select sum(row_x) from table_xx where class_id=1)
+
(select sum(row_y) from table_xx where class_id=1) )
Table xx
row_id class_id row_x row_y
1 1 4 5
2 1 5 6
3 2 6 7
4 1 7 8
Table yy
class_id sum_of_x_and_y
1 35
2 13
but instead of setting the class_id manually, I would love to do something like inner-join update, but I'm working with 15k+ of records.
Here is a query that should do the job
UPDATE table_yy, (
SELECT class_id, SUM(table_xx.row_x + table_xx.row_y) AS sum_of_x_and_y
FROM table_xx
GROUP BY table_xx.class_id
) AS table_sum
SET table_yy.sum_of_x_and_y = table_sum.sum_of_x_and_y
WHERE table_yy.class_id = table_sum.class_id
Your approach is fine. You just want a correlated subquery:
update table_yy yy
set sum_of_x_and_y = (select sum(xx.row_x) + sum(xx.row_y)
from table_xx xx
where xx.class_id = yy.class_id
);
Under many circumstances, this will have better performance, particularly if you have an index on table_xx(class_id)
.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.