简体   繁体   中英

Oracle 12c - How to insert primary key of another table multiple times into a table

I have TABLE_A with the columns:

table_id (PK) number;
table_1_id number;
table_2_id number;

and TABLE_B :

table_id number;
table_1_id number;
table_2_id number;
table_key number;
table_key_data varchar2(15);

I need to insert two records for each missing TABLE_A.table_id into TABLE_B .

This is how the data looks before:

table_1_id table_2_id table_id table_key table_key_data
1          123        12345    1         1111
1          123        12345    2         ABC

So if TABLE_A has the following table_id 's:

    12345
    23456
    34567    
..plus hundreds/thousands more

TABLE_B should look like this after the insert:

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.

There may be more than 2 table_key 's for each table_id . So I need something like this:

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)

How can I achieve this?

You can run 2 INSERT statements. Just add in your WHERE statement TABLE_A.TABLE_ID NOT IN (SELECT table_id FROM TABLE_B WHERE table_key = <1 or 2 depending on which insert you're doing>). This will allow you to do one at a time.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM