4

如何在更新后的表上使用多个联接更新 SQL Server 上的表?在 MySQL 中,您可以为更新的表定义别名,但它如何与 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.*
4

4 回答 4

8

这适用于 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

我想问题的出现是因为您尝试重新设置别名,但我不确定。

于 2012-05-29T15:02:12.020 回答
1

您可以将所有内容移到 WHERE 子句中:

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

不是我最喜欢的连接样式,但它应该足以满足您的目的。

但是,在 TSQL 中,我真的会执行以下操作。创建一个查询,返回每个 id 的新更新值。然后使用以下格式编写查询:

with toupdate as (<the query>)
    update o
        set o.parent_id = toupdate.id
    from toupdate
    where o.id = toupdate.id       
于 2012-05-29T14:30:30.563 回答
1

您只需要删除 o 表的别名

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
于 2012-05-29T14:35:42.857 回答
-2

自加入更新

update #table1 set column1= b.column2
from #table1 #table1, #table1 b where #table1.Id=b.Id  
于 2018-08-28T03:58:27.657 回答