使用自联接进行更新
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了使用自联接进行更新相关的知识,希望对你有一定的参考价值。
我想更新一个表,表明某些行是其他行的父级,所以我在表中添加了一个“parentid”列。以下查询查找所有父项:
SELECT ca1.id, ca2.id
FROM contactassociations ca1
JOIN contactassociations ca2 ON (ca1.contactid = ca2.contactid)
where ca1.entitytable = 'EMPLOYER' AND
ca2.entitytable = 'CLIENT';
但是当我尝试调整该语法来进行更新时,它不起作用:
UPDATE contactassociations ca1
SET ca1.parentid = ca2.id
JOIN contactassociations ca2 ON (ca1.contactid = ca2.contactid)
WHERE ca1.entitytable = 'EMPLOYER' AND ca2.entitytable = 'CLIENT';
我明白了:
Error starting at line 6 in command:
UPDATE contactassociations ca1
SET ca1.parentid = ca2.id
JOIN contactassociations ca2 ON (ca1.contactid = ca2.contactid)
WHERE ca1.entitytable = 'EMPLOYER' AND ca2.entitytable = 'CLIENT'
Error at Command Line:7 Column:28
Error report:
SQL Error: ORA-00933: SQL command not properly ended
00933. 00000 - "SQL command not properly ended"
*Cause:
*Action:
注意,第7行第28列是“SET”行的结尾。
答案
Oracle不支持JOIN
语句中的UPDATE
子句。
用这个:
MERGE
INTO contactassociations ca1
USING contactassociations ca2
ON (
ca1.contactid = ca2.contactid
AND ca1.entitytable = 'EMPLOYER'
AND ca2.entitytable = 'CLIENT'
)
WHEN MATCHED THEN
UPDATE
SET parentid = ca2.id
另一答案
我发现以下样式更易于阅读,但您需要在UPDATE关键字之后使用别名,而不是表名:
UPDATE ca1
SET ca1.parentid = ca2.id
FROM contactassociations ca1
LEFT JOIN contactassociations ca2 ON (ca1.contactid = ca2.contactid)
WHERE ca1.entitytable = 'EMPLOYER' AND ca2.entitytable = 'CLIENT'
另一答案
-- Method #1
update emp set MANAGERNAME= mgr.EMPNAME
FROM SelfJoinTable emp , SelfJoinTable mgr where emp.MANAGERID = mgr.EMPID
-- Method #2
update emp
set MANAGERNAME= mgr.EMPNAME
FROM SelfJoinTable emp
LEFT OUTER JOIN SelfJoinTable mgr
ON emp.MANAGERID = mgr.EMPID
-- Method #3
update emp
set MANAGERNAME= mgr.EMPNAME
FROM SelfJoinTable emp
JOIN SelfJoinTable mgr
ON emp.MANAGERID = mgr.EMPID
-- Method #4
update emp
set MANAGERNAME= mgr.EMPNAME
FROM SelfJoinTable emp
inner JOIN SelfJoinTable mgr
ON emp.MANAGERID = mgr.EMPID
以上是关于使用自联接进行更新的主要内容,如果未能解决你的问题,请参考以下文章