簡體   English   中英

Oracle SQL如何使用從子查詢派生的正確和不正確的外鍵更新外鍵?

[英]Oracle SQL how do I update a foreign key using a correct and incorrect foreign key derived from a subquery?

我有以下示例表:

table1
id      values
1       arbitraryvalue
2       arbitraryvalue
3       arbitraryvalue
4       arbitraryvalue
5       arbitraryvalue
6       arbitraryvalue
7       arbitraryvalue
8       arbitraryvalue
9       arbitraryvalue
10      arbitraryvalue

通過使用子查詢,我得到下表:

subqueryTable
correctId   incorrectId
2           4
8           6
10          5

我有第三個表,使用id作為外鍵。

table2
foreignKeyId    otherColumns
2               somedatahere
4               somedatahere
1               somedatahere
5               somedatahere

我想做的是刪除ID錯誤的行,因為它們是ID正確的行的意外重復。 但是,為此,我需要使用正確的ID更新外鍵。

如何更新外鍵?

我需要類似的東西

Update table2
SET foreignKeyId = subqueryTable.correctId
WHERE foreignKeyId = subqueryTable.incorrectId

您只需要更新具有無效標識符的行:

update table2 t2 set foreignKeyId = (select correctid from subqueryTable 
                                      where t2.ForeignKeyId = incorrectId)
  where foreignKeyId in (select incorrectid from subqueryTable);

您可以在更新中使用相關子查詢:

UPDATE table2 t2
SET foreignKeyId = (SELECT s.correctId
           FROM   subqueryTable s
           WHERE  t2.foreignKeyId = s.incorrectId)
;

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM