简体   繁体   中英

How to UPDATE a table on SQL Server with multiple Joins on the updated table? (FROM FROM JOIN)

How to UPDATE a table on SQL Server with multiple Joins on the updated table? In MySQL you can define a Alias for updated table, but how does it works with TSQL.

 UPDATE recert.ou              --#1-- In MSSQL/TSQL no alias allowed
SET parent_id = o2.ID
    FROM recert.ou as O              
    JOIN recert.country C ON C.ID = O.country_id
    JOIN recert.ou P ON O.parent_id = P.ID and p.country_id <> O.country_id     
    JOIN recert.ou o2 on o2.name = p.name and c.ID = o2.country_id              
    JOIN recert.country as c2 on c2.ID = o2.country_id
           WHERE O.ID = o2.ID

-

RESULT: *The table 'o' is ambiguous.*

This works on Sql Fiddle .

UPDATE o
SET parent_id = o2.ID
    FROM recert O
    JOIN c C ON C.ID = O.country_id
    JOIN recert P ON O.parent_id = P.ID and p.country_id <> O.country_id
    JOIN recert o2 on o2.name = p.name and c.ID = o2.country_id
    JOIN c c2 on c2.ID = o2.country_id
WHERE O.ID = o2.ID

I suppose the problem arose because you tried to re-alias an alias, but I'm not sure.

You can move everything into the WHERE clause:

UPDATE o              --#1-- In MSSQL/TSQL no alias allowed
    SET parent_id = o2.ID
    FROM c, o, o o2, C c2
    Where o.country_id = c.id and o.parent_id = p.id and p.country_id <> O.country_id and
          o2.name = p.name and c.ID = o2.country_id and c2.ID = o2.country_id

This is not my favorite style of joins, but it should suffice for your purposes.

However, in TSQL, I would really do the following. Create a query that returns the new update value for each id. Then write a query with the following format:

with toupdate as (<the query>)
    update o
        set o.parent_id = toupdate.id
    from toupdate
    where o.id = toupdate.id       

You just need to remove the alias name for o table

UPDATE o              
SET parent_id = o2.ID
FROM o               
JOIN c C ON C.ID = o.country_id
JOIN o P ON o.parent_id = P.ID and p.country_id <> o.country_id   
JOIN o o2 on o2.name = p.name and c.ID = o2.country_id             
JOIN c c2 on c2.ID = o2.country_id
 WHERE o.ID = o2.ID

self joined update

update #table1 set column1= b.column2
from #table1 #table1, #table1 b where #table1.Id=b.Id  

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM