使用内部联接更新查询-使用更新的列值到同一表的另一列

时间:2019-06-06 06:25:39

标签: mysql sql database

我想使用相同的SQL查询从同一表中的另一个更新列中更新一个列评估器。更新查询中加入了3个表,如下所示:

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

任何帮助将不胜感激

2 个答案:

答案 0 :(得分:0)

由于字段不明确,您需要在SET语句中指定表。

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"

答案 1 :(得分:0)

根据您的评论,如果您希望在new_valueCol1列中更新Col2,则可以使用以下更新块

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