Search code examples
mysqlsqlinner-join

Update MYSQL Table from multiple rows in another table


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.


Solution

  • 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