在更新语句中连接多个表

时间:2012-07-16 20:12:48

标签: sql-server

我正在尝试在更新语句中加入三个表,但到目前为止我还没有成功。我知道这个查询适用于连接两个表:

update table 1
set x = X * Y
from table 1 as t1 join table 2 as t2 on t1.column1 = t2.column1

但是,就我而言,我需要加入三个表:

update table 1
set x = X * Y
from table 1 as t1 join table 2 as t2 join table3 as t3 
on t1.column1 = t2.column1 and t2.cloumn2 = t3.column1

不行。我还尝试了以下查询:

update table 1
set x = X * Y
from table 1, table 2, table 3
where column1 = column2 and column2= column3

有谁知道实现这个目标的方法?

1 个答案:

答案 0 :(得分:16)

你绝对不想使用table, table, table语法; here's why。对于您的中间代码示例,连接语法遵循与SELECT大致相同的UPDATE规则。 JOIN t2 JOIN t3 ON ...无效,但JOIN t2 ON ... JOIN t3 ON有效。

所以这是我的提案,但应该更新为完全符合y来自的地方:

UPDATE t1
  SET x = x * y  -- should either be t2.y or t3.y, not just y
  FROM dbo.table1 AS t1
  INNER JOIN table2 AS t2
  ON t1.column1 = t2.column1
  INNER JOIN table3 AS t3
  ON t2.column2 = t3.column1;