【问题标题】:Insert records from 1st table to 2nd table only when the record is not present in the 2nd table仅当记录不存在于第二个表中时,才将记录从第一个表插入到第二个表
【发布时间】:2019-12-12 10:06:18
【问题描述】:

我有一张表与第二张表的表结构相同,我只需要将 table1 中的记录插入到 table2 中

insert into table2(select * from table1);

表 2 在其中一个字段 say(id) 中有一个主键,并且有人插入了与该主键对应的数据

table1          table2

id | name      id | name
 1 | new1       1 | old1
 2 | new2       4 | new4
 3 | new3       3 | old3
 5 | new5       6 | old6

我只需要将那些没有填充主键的记录插入到表 2 中。

插入后的表 2 应该是这样的


table 2
id | name
1  | old1
2  | new2
3  | old3
4  | new4
5  | new5
6  | old6

最简单的方法是什么?

【问题讨论】:

  • 我建议你设置一个游标,从表1中选择所有不在两个中的记录,然后遍历它们并插入它们。
  • @TineO: 效率最低的光标

标签: sql oracle sql-insert


【解决方案1】:

使用 NOT EXISTS 条件仅从 table1 中获取那些在 table2 中不存在的行:

insert into table2 (id, name)
select t1.id, t1.name
from table1 t1
where not exists (select *
                  from table2 t2
                  where t2.id = t1.id);

【讨论】:

    【解决方案2】:

    您可以只使用带有 INSERT WHEN NOT MATCHED 的 MERGE 语句:

    MERGE INTO table2 t2
    USING table1 t1
      ON t1.id = t2.id
    WHEN NOT MATCHED
    THEN 
       INSERT INTO table2
         (id, name)
       VALUES
          (t1.id, t1.name)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2014-03-03
      • 2019-12-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-04-07
      • 2021-11-26
      • 1970-01-01
      相关资源
      最近更新 更多