gpt4 book ai didi

postgresql - 使用 postgres 将大量行从一个表移动到另一个新表的有效方法

转载 作者:行者123 更新时间:2023-11-29 11:31:36 35 4
gpt4 key购买 nike

我正在为实时项目使用 PostgreSQL 数据库。其中,我有一个包含 8 列的表。此表包含数百万行,因此为了加快表中的搜索速度,我想删除此表中的旧条目并将其存储到新的另一个表中。

为此,我知道一种方法:

  • 首先选择一些行
  • 创建新表
  • 将这些行存储在那个表中
  • 而不是从主表中删除。

但是耗时太长,效率不高。

所以我想知道在 postgresql 数据库中执行此操作的最佳方法是什么?

Postgresql 版本:9.4.2.
大约行数:8000000
我要移动行:2000000

最佳答案

您可以使用 CTE(公用表表达式)在单个 SQL 语句 (more in the documentation) 中移动行:

with delta as (
delete from one_table where ...
returning *
)
insert into another_table
select * from delta;

但是仔细想想你是否真的需要它。就像评论中的 a_horse_with_no_name 所说,调整您的查询可能就足够了。

关于postgresql - 使用 postgres 将大量行从一个表移动到另一个新表的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35837354/

35 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com