【问题标题】:Oracle 12c - How to insert primary key of another table multiple times into a tableOracle 12c - 如何将另一个表的主键多次插入表中
【发布时间】:2017-11-17 22:03:00
【问题描述】:

我有 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 可能有超过 2 个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)

我怎样才能做到这一点?

【问题讨论】:

  • 你需要说明你是如何获取表b中的数据的。
  • @AbBennett 请立即查看我的帖子。

标签: sql oracle sql-insert oracle12c


【解决方案1】:

您可以运行 2 个 INSERT 语句。只需添加您的 WHERE 语句 TABLE_A.TABLE_ID NOT IN(SELECT table_id FROM TABLE_B WHERE table_key = )。这将允许您一次做一个。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    • 2023-03-17
    • 1970-01-01
    相关资源
    最近更新 更多