Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Joining multiple tables within an update statement

Tags:

sql-server

I am trying to join three tables within an update statement, but I have been unsuccessful so far. I know this query works for joining two tables:

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

However, in my case, I need to join three tables so:

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

Will not work. I also tried the following query:

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

Does anyone know of a method to accomplish this?

like image 882
Rick Avatar asked Jul 16 '12 20:07

Rick


1 Answers

You definitely don't want to use table, table, table syntax; here's why. As for your middle code sample, join syntax follows roughly the same rules for SELECT as it does for UPDATE. JOIN t2 JOIN t3 ON ... is not valid, but JOIN t2 ON ... JOIN t3 ON is valid.

So here is my proposal, though it should be updated to fully qualify where y comes from:

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;
like image 63
Aaron Bertrand Avatar answered Oct 20 '22 15:10

Aaron Bertrand