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

梦想的初衷 提交于 2019-12-02 12:21:29

问题


I'd like to update table1 based upon a sum principally applied on table2 but including a single value from table 3.

table2 has a column that's FKd to table1's id column, and the sum is based upon them matching.

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;

That doesn't work for me.

Many thanks in advance!

EDIT: Error Given

#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;'

回答1:


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;

There is no "FROM table2,table1" in the area marked with astericks above.




回答2:


Try this:

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



回答3:


try this:

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


来源:https://stackoverflow.com/questions/12755925/update-table1-set-column1-sumtable2-table3-where-table2-id1-id1-where

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!