简体   繁体   English

从另一个表中的多行更新MYSQL表

[英]Update MYSQL Table from multiple rows in another table

I'm trying to update table yy from table xx results by doing sum. 我正在尝试通过求和从表xx结果中更新表yy

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 表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 表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. 但是我不想做手动设置class_id的事情,而是想做诸如内部联接更新之类的事情,但是我正在处理15k +条记录。

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) . 在许多情况下,这将具有更好的性能,尤其是在table_xx(class_id)上具有索引的情况下。

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

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