首页 > 解决方案 > 将记录从一个表插入到另一个表,然后删除插入的记录

问题描述

我正在使用此查询将记录从一个表插入到另一个表中:

insert into watched_url_queue_work select * from watched_url_queue

在冲突中什么都不做

目标表上的唯一约束意味着并非全部都被插入。

我现在要做的是删除我刚刚插入的所有记录,但我不确定语法。

我想要类似的东西(查询不起作用只是我的猜测):

delete from watched_url_queue q
where q.target_domain_record_id in
      (
        insert into watched_url_queue_work select * from watched_url_queue
        on conflict do nothing
        returning watched_url_queue_work.target_domain_record_id
      )

标签: postgresqlpostgresql-10

解决方案


您可以使用CTE执行此操作:

with inserted as (
  insert into watched_url_queue_work
  select * from watched_url_queue
  on conflict do nothing
  returning watched_url_queue_work.target_domain_record_id
)
delete from watched_url_queue q
using inserted
where q.target_domain_record_id = inserted.target_domain_record_id;

(该q.target_domain_record_id in (select … from inserted)方法也有效。)


推荐阅读