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

编程入门 行业动态 更新时间:2024-10-26 05:34:14
本文介绍了使用postgres将大量行从一个表移动到另一个新表的有效方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

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

I am using PostgreSQL database for live project. In which, I have one table with 8 columns. This table contains millions of rows, so to make search faster from table, I want to delete and store old entries from this table to new another table.

为此,我知道一种方法:

To do so, I know one approach:

  • 首先选择一些行
  • 创建新表
  • 将此行存储在该表中
  • 比从主表中删除。
  • first select some rows
  • create new table
  • store this rows in that table
  • than delete from main table.

但是它花费了太多时间,而且效率不高。

But it takes too much time and it is not efficient.

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

So I want to know what is the best possible approach to perform this in postgresql database?

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

Postgresql version: 9.4.2. Approx number of rows: 8000000 I want to move rows: 2000000

推荐答案

您可以使用CTE(公用表表达式)在单个SQL语句中移动行(文档中的更多内容):

You can use CTE (common table expressions) to move rows in a single SQL statement (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一样,调整查询可能就足够了。

But think carefully whether you actually need it. Like a_horse_with_no_name said in the comment, tuning your queries might be enough.

更多推荐

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

本文发布于:2023-11-29 18:22:17,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1647221.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:方法   postgres

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!