Mise à jour avec autojointure
-
24-09-2019 - |
Question
Je veux mettre à jour un tableau pour indiquer que certaines lignes sont les parents des autres, alors j'ai ajouté une colonne « parentid » à la table. La requête suivante trouve tous les 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';
mais lorsque je tente d'adapter cette syntaxe pour faire la mise à jour, il ne fonctionne pas:
UPDATE contactassociations ca1
SET ca1.parentid = ca2.id
JOIN contactassociations ca2 ON (ca1.contactid = ca2.contactid)
WHERE ca1.entitytable = 'EMPLOYER' AND ca2.entitytable = 'CLIENT';
Je reçois:
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:
Notez que la ligne 7 colonne 28 est la fin de la ligne "SET".
La solution
Oracle ne supporte pas la clause de JOIN
dans les déclarations de UPDATE
.
Utilisez ceci:
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
Autres conseils
Je trouve le plus simple de style suivant pour lire, mais vous devez utiliser un alias après le mot clé UPDATE, pas le nom de la table:
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
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow