[英]Oracle 12c - How to insert primary key of another table multiple times into a table
我有TABLE_A
的列:
table_id (PK) number;
table_1_id number;
table_2_id number;
和TABLE_B
:
table_id number;
table_1_id number;
table_2_id number;
table_key number;
table_key_data varchar2(15);
我需要為每個缺少的TABLE_A.table_id
插入兩條記錄到TABLE_B
。
這是數據之前的樣子:
table_1_id table_2_id table_id table_key table_key_data
1 123 12345 1 1111
1 123 12345 2 ABC
因此,如果TABLE_A
具有以下table_id
:
12345
23456
34567
..plus hundreds/thousands more
插入后, TABLE_B
應該如下所示:
table_1_id table_2_id table_id table_key table_key_data
1 123 12345 1 1111
1 123 12345 2 ABC
1 123 23456 1 1111
1 123 23456 2 ABC
1 123 34567 1 1111
1 123 34567 2 ABC
...plus remaining hundreds/thousands more.
每個table_id
可能有兩個以上的table_key
。 所以我需要這樣的東西:
INSERT INTO TABLE_B (SELECT 1,123,TABLE_A.TABLE_ID, 1 for the first record and 2 for second record etc, CASE WHEN table_key = 1 THEN '1111' WHEN table_key = 2 THEN '1111111' END FROM TABLE_A WHERE TABLE_A.TABLE_ID NOT IN (SELECT table_id FROM TABLE_B)
我該如何實現?
您可以運行2條INSERT語句。 只需在WHERE語句中添加TABLE_A.TABLE_ID NOT IN(從TABLE_B中選擇TABLE_ID,在其中table_key = <1或2,具體取決於您要插入哪個>)。 這樣一來,您就可以一次做一個。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.