首页 > 解决方案 > 从另一个表中的多行更新 MYSQL 表

问题描述

我正在尝试通过求和来从表 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) )

表二十

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+的记录。

标签: mysqlsqlinner-join

解决方案


这是一个应该完成这项工作的查询

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

推荐阅读