【问题标题】:Oracle 12c - insert duplicates with sequence from another tableOracle 12c - 从另一个表中插入重复序列
【发布时间】:2019-03-04 17:58:58
【问题描述】:

我有以下插入语句失败,违反了 ORA-00001 唯一约束(这是违反 PK 的)。 PK 在 c_id,f_id 上。

INSERT 
   INTO ab (c_id
          , d_amt
          , e_date
          , f_id)
   SELECT c_id
        , d_amt
        , e_date
        , (SELECT NVL(MAX(f_id) + 1,1) --this is causing the ORA-00001 error on duplicate c_id's
             FROM ab
            WHERE c_id = cx.c_id) f_id
     FROM xx cx

我的目标是将数据从 xx 插入 ab,如果 xx 中有重复的 c_id 值,那么 insert 语句应该在第一个之后的每个重复值将 f_id 值增加 1。

【问题讨论】:

  • 您需要调查merge 声明。

标签: sql oracle sql-insert


【解决方案1】:

您可以将您的子查询更改为您外连接的内联视图,然后使用分析函数来递增:

INSERT 
   INTO ab (c_id
          , d_amt
          , e_date
          , f_id)
   SELECT cx.c_id
        , cx.d_amt
        , cx.e_date
        , NVL(ab2.f_id, 0) + ROW_NUMBER() OVER (PARTITION BY cx.c_id ORDER BY NULL)
     FROM xx cx
     LEFT JOIN (SELECT c_id, MAX(f_id) as f_id FROM ab GROUP BY c_id) ab2
     ON ab2.c_id = cx.c_id

db<>fiddle demo

ORDER BY NULL 有点绕;如果您关心插入行中的序列是什么,您可以按cx 提供的其他列中的一个或多个进行排序。

【讨论】:

    猜你喜欢
    • 2023-03-09
    • 2012-03-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-04-18
    • 2013-12-29
    • 1970-01-01
    • 2017-12-10
    相关资源
    最近更新 更多