我有3张桌子:
Table1
-------
ID
Field1
Field2
Table2
_______
ID
Name
Table2_OLD
____________
ID
Name
我需要将表2中的ID更新为Table2中的ID,其中Table2.Name = Table2_OLD.Name
Table2和Table2_OLD中的ID不同,只有名称才能用于获取正确的ID:
SELECT Table2.ID
FROM Table2
INNER JOIN Table2_OLD ON Table2.Name=Table2_OLD.Name
我写了以下更新声明:
UPDATE Table1 SET Table1.ID=(SELECT DISTINCT t2.ID
FROM Table2 t2
INNER JOIN Table2_OLD t3
ON t2.Name=t3.Name
AND t2.ID=Table1.ID)
但它给了我一个错误
无法将Table1.ID更新为null`
我尝试使用
UPDATE Table1 SET Table1.ID = (SELECT DISTINCT t2.ID
FROM Table2 t2
INNER JOIN Table2_OLD t3
ON t2.Name=t3.Name
AND t2.ID=Table1.ID
AND NOT t2.ID is null)
但得到了同样的错误。
有人可以帮忙吗?
答案 0 :(得分:1)
尚未对其进行测试,但Oracle中的相关更新应该有效:
UPDATE table1 t1
SET id = (SELECT DISTINCT t2.id
FROM table2 t2
JOIN table2_old t3 ON
t2.name = t3.name
WHERE t3.id = t1.id
)
WHERE EXISTS (
SELECT 1
FROM table2 t2
WHERE t3.id = t1.id
)
答案 1 :(得分:1)
如果您想JOIN
更新,可以试试这个。
UPDATE (
SELECT t2.ID t2ID,t1.ID t1ID
FROM Table1 t1
INNER JOIN Table2_OLD t2Old ON t1.ID= t2Old.ID
INNER JOIN Table2 t2 ON t2.Name=t2Old.Name
WHERE t2.ID is NOT null
)
SET t1ID = t2ID