mezamorphic mezamorphic - 2 months ago 10
SQL Question

UPDATING a table based on a FROM clause, how do I limit with WHERE?

I have a SQL UPDATE clause which looks like:

UPDATE table
SET column =value
FROM
(SELECT bla bla FROM bla bla WHERE col = val)
JOIN
(SELECT bla bla FROM bla bla WHERE col = val)


I want to limit the UPDATE to WHERE a particular column is equal to a particular value.

It doesnt appear to be legal to insert the WHERE after the JOIN or after the SET? I thought I had already limited the update using the JOIN but it doesn't appear so.

Where can I insert my WHERE clause?

Answer

If this vlaue is a literal value, not a value coming form either of these joined tables, then you can do this:

UPDATE table t1
SET t1.column = value -- literalvalue
FROM
(
   SELECT bla bla FROM bla bla)
   JOIN
   (
      SELECT bla bla FROM bla bla
   ) on thefirstblah = somethingfromthesecondblah
) t1

Or:

UPDATE table t1
SET t1.column = value -- literalvalue
FROM
(
   SELECT bla bla FROM bla bla
   JOIN anotherbla ON ----
) t1;

However, if this value is coming from one of the joined table:

UPDATE table t1
SET t1.column = t2.value 
FROM table t1
JOIN table2 t2 ON ---
Comments