【问题标题】:Insert new/Changes from one table to another in Oracle SQL在 Oracle SQL 中将新表/更改从一个表插入另一个表
【发布时间】:2014-07-19 17:30:36
【问题描述】:

我有两个列数相同的表:-表 A 和表 B 每天我将数据从表 B 插入表 A。现在插入查询正在工作

insert into table_a (select * from table_b);

但是通过这个插入,之前插入的相同数据也被插入。我只想要那些新的或从旧数据更改的行。这是怎么做到的?

【问题讨论】:

  • 看看快速刷新的物化视图。如果你的 table_a 是只读的(除了这个插入选择之外没有其他操作被执行),这可能是最简单的选择

标签: sql oracle


【解决方案1】:

你可以使用minus:

insert into table_a
    select *
    from table_b
    minus
    select *
    from table_a;

这里假设“重复”是指所有列都是重复的。

【讨论】:

  • 此外,如果(偶然)您有一个日期修改列,请仅选择表 b 中修改的日期 > 表 a 中的最大值。
【解决方案2】:

如果您有时间戳字段,您可以使用它将记录限制为在上次复制之后创建的记录。

另一个选项是,假设您有一个主键(在我的示例中为id 列),您可以使用它来了解是否已经复制了一条记录,您可以创建一个表c(具有相同的结构作为ab) 并执行以下操作:

insert into table c 
  select a.* from table a
  left join table b on (a.id=b.id)
  where b.id is null;

insert into table b select * from table c;

truncate table c;

您需要调整此查询以使用实际的主键。

希望这会有所帮助!

【讨论】:

    【解决方案3】:

    如果表有一个主键或唯一键,那么您可以在反连接中利用它:

    insert into table_a
    select *
    from table_b b
    where not exists (
      select null
      from table_a a
      where
        a.pk_field_1 = b.pk_field_1 and
        a.pk_field_2 = b.pk_field_2
    )
    

    【讨论】:

      【解决方案4】:

      你没有说你的钥匙是什么。假设您有一个密钥 ID,即您只需要尚未在表 A 中的 ID。您也可以为此使用 Merge-Statement:

      MERGE INTO A USING B ON (A.ID = B.ID)
      WHEN NOT MATCHED THEN INSERT (... columns of A) VALUES (... columns of B)
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2012-05-01
        • 2018-07-01
        • 1970-01-01
        • 2013-12-14
        • 1970-01-01
        • 1970-01-01
        • 2020-04-07
        相关资源
        最近更新 更多