繁体   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