【问题标题】:Insert records from one table to another and then delete inserted records将记录从一个表插入到另一个表,然后删除插入的记录
【发布时间】:2020-08-09 23:06:46
【问题描述】:

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

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
      )

【问题讨论】:

标签: postgresql postgresql-10


【解决方案1】:

您可以使用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) 接近 works as well。)

【讨论】:

  • 谢谢。我尝试了这两种方式,但查询运行了很长时间(20 分钟以上),我必须将其切断,因为如果需要这么长时间,这将无法在生产中工作。该表非常大(几百万条记录)。我可以增加 postgresql 中的任何特定设置以使其运行得更好吗?查询运行时,服务器有 60gb 的可用内存。
  • 也许您也可以尝试编写一个过程/DO block,使用cursor 或以1000 个为单位执行此操作,这样临时inserted 表就不会变得太大。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-17
  • 2017-08-01
  • 1970-01-01
  • 1970-01-01
  • 2021-01-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多