[英]Oracle 12c - How to insert primary key of another table multiple times into a table
I have TABLE_A
with the columns: 我有
TABLE_A
的列:
table_id (PK) number;
table_1_id number;
table_2_id number;
and TABLE_B
: 和
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
. 我需要为每个缺少的
TABLE_A.table_id
插入两条记录到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: 因此,如果
TABLE_A
具有以下table_id
:
12345
23456
34567
..plus hundreds/thousands more
TABLE_B
should look like this after the insert: 插入后,
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.
There may be more than 2 table_key
's for each table_id
. 每个
table_id
可能有两个以上的table_key
。 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. 您可以运行2条INSERT语句。 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>).
只需在WHERE语句中添加TABLE_A.TABLE_ID NOT IN(从TABLE_B中选择TABLE_ID,在其中table_key = <1或2,具体取决于您要插入哪个>)。 This will allow you to do one at a time.
这样一来,您就可以一次做一个。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.