Update with self-join

我是研究僧i 提交于 2019-12-01 05:35:59

问题


I want to update a table to indicate that some rows are parents of others, so I added a "parentid" column to the table. The following query finds all the parents:

SELECT ca1.id, ca2.id 
FROM contactassociations ca1
JOIN contactassociations ca2 ON (ca1.contactid = ca2.contactid)
where ca1.entitytable = 'EMPLOYER' AND
ca2.entitytable = 'CLIENT';

but when I try to adapt that syntax to do the update, it doesn't work:

UPDATE contactassociations ca1
SET    ca1.parentid = ca2.id
JOIN  contactassociations ca2 ON (ca1.contactid = ca2.contactid)
WHERE ca1.entitytable = 'EMPLOYER' AND ca2.entitytable = 'CLIENT';

I get:

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:

Note that line 7 column 28 is the end of the "SET" line.


回答1:


Oracle does not support JOIN clause in UPDATE statements.

Use this:

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



回答2:


I find the following style simpler to read, but you need to use an alias after the UPDATE key word, not the table name:

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'



回答3:


-- 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


来源:https://stackoverflow.com/questions/2380353/update-with-self-join

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!