簡體   English   中英

Oracle 12c-如何將另一個表的主鍵多次插入表中

[英]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.

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