I want to update one column valur from the another updated column in same table with same SQL query. There are 3 tables joined in update query as below:
UPDATE table1
INNER JOIN table2 ON table2.id = table1.pid
INNER JOIN table3 ON table3.id = table2.cid
SET
table1.col1 = "1+2+3",
table1.col2 = table1.col1 + 5
WHERE
table1.id = 5
Any help would be appreciated
You need to specify the table in the SET statement as the fields are ambiguous.
UPDATE table1
INNER JOIN table2 ON table2.id = table1.pid
INNER JOIN table3 ON table3.id = table2.cid
----- (Option1 - Shifting values in a single table) -----
SET
table1.col1 = table1.col2,
table1.col2 = table1.col3,
table1.col3 = table1.col4
----- (Option2 - Assigning values across tables) -----
SET
table1.col1 = table2.col2,
table2.col1 = table3.col2,
table3.col1 = table1.col2
----- (Option2 - Updating values across tables) -----
SET
table1.col1 = table1.col2 + 1,
table2.col1 = table2.col2 - 1,
table3.col1 = table3.col2 + table3.col1
WHERE
table1.id = 5
NB: SET commands are done in the order listed so may you need to swop the two lines around in the set to get what you want.
SET
table1.col2 = table1.col1 + 5,
table1.col1 = "1+2+3"
According to your comment, if you want the new_value
to be updated in Col1
and Col2
columns, you can use the following update block
UPDATE table1
INNER JOIN table2 ON table2.id = table1.pid
INNER JOIN table3 ON table3.id = table2.cid
SET
table1.col1 = new_value,
table1.col2 = new_value
WHERE
table1.id = 5
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.