从另一个表

时间:2018-06-09 07:45:27

标签: mysql sql inner-join

我正在尝试通过总结从表格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 +的记录。

2 个答案:

答案 0 :(得分:2)

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

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

答案 1 :(得分:0)

你的方法很好。您只需要一个相关的子查询:

timeTag= recordData & 65535;
channel = (recordData>> 16) & 0x800;
route   = (recordData>> 28) & 2;
valid = (recordData>> 30) & 1;
reserved = (recordData>> 31) & 1;

在许多情况下,这会有更好的表现,特别是如果你有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 ); 的索引。