繁体   English   中英

使用 CTE 执行插入语句

[英]Performance of insert statement with CTE

我有 2 个外部表,我们称它们为 A 和 B。我还有一个内部表 C。A 和 B 有一些重叠的值。 我想编写一个程序,将 A 中的所有值写入 C,然后将 B 中所有我还没有(从 A)写入 C 的值。所以首先将 A 写入 C,然后写入所有尚未写入的剩余数据从 B 写到 C。基本上是这样的:

Write A -> C 
Write B where not already written by A -> C

我的第一次尝试看起来像这样

insert into C (select * from A);
insert into C (select * from B where b.id not in (select a.id from a));

我的表很大,数据链接很慢,所以这不会发生,因为它需要很长时间。 我认为问题在于它必须为 B 的每个条目执行(select a.id from a) 。所以我认为使用 CTE 肯定会有所帮助:

insert into C (select * from A);
insert into C 
  with A_values as (select a.id from a)
  select * from b where b.id not in a.values;

但是,这仍然不会终止(花费太长时间)。 有什么想法可以解决这个问题吗?

我想你在描述两个插入:

insert into c ( . . . )
    select . . .
    from a;

insert into c ( . . . )
    select . . .
    from b
    where not exists (select 1 from c where b.id = c.id);

为了提高性能,您需要在c(id)或任何用于比较的列上建立索引。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM