UPDATE table1 SET column1 = (SUM(table2{& table3}

2019-03-01 12:24发布

问题:

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