UPDATE table1 SET column1 =(SUM(table2 {& table3} WHERE table2_id1 = id1)WHERE id1 = table2_id1

时间:2012-10-06 01:31:51

标签: mysql sum sql-update where multiple-tables

我想基于主要应用于table2但包含表3中的单个值的总和来更新table1。

table2有一个列为FKd到table1的id列,并且总和基于它们的匹配。

UPDATE table1, table2 
SET table1.column1 = 
(SELECT SUM( (SELECT constant FROM table3) +
          (SELECT table2.sum_number 
           WHERE table2.table2_id1 = table1.id) ) ) 
WHERE table1.id = table2.table2_id1;

这对我不起作用。

非常感谢提前!

编辑:错误指定

#1064 - You have an error in your SQL syntax; check the manual that corresponds 
 to your MySQL server version for the right syntax to use near 
 'WHERE table2.table2_id1 = table1.id) ) ) WHERE table1.id = table2.table2_id1;'

3 个答案:

答案 0 :(得分:3)

UPDATE table1, table2 
SET table1.column1 = 
(
    SELECT SUM( 
        (SELECT constant FROM table3) +
        (SELECT table2.sum_number *** WHERE table2.table2_id1 = table1.id) 
    ) 
) 
WHERE table1.id = table2.table2_id1;

上面标有星号的区域内没有“FROM table2,table1”。

答案 1 :(得分:0)

试试这个:

UPDATE 
    table1 t1
INNER JOIN
    table2 t2 ON t2.table2_id1 = t1.id
SET
    t1.column1 = (SELECT constant FROM table3) + t2.sum_number

答案 2 :(得分:0)

试试这个:

Update table1 t1 join table2 t2 on t1.id = t2.table2_id1
SET t1.column1 = (SELECT constant FROM table3) + t2.sum_number