[英]Update MYSQL Table from multiple rows in another table
我正在嘗試通過求和從表xx結果中更新表yy 。
例如(語法是抽象的):
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) )
表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
表yy
class_id sum_of_x_and_y
1 35
2 13
但是我不想做手動設置class_id的事情,而是想做諸如內部聯接更新之類的事情,但是我正在處理15k +條記錄。
這是應該做的查詢
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
您的方法很好。 您只需要一個相關的子查詢:
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
);
在許多情況下,這將具有更好的性能,尤其是在table_xx(class_id)
上具有索引的情況下。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.