在 PostgreSQL 中从 SELECT 创建 INSERT INTO

Kok*_*zzu 4 postgresql-9.5

如何创建INSERT INTO语句,使用SELECT语句?我需要它,因为我想从表中删除 10k 条记录,但是如果有一天需要恢复其中的某些记录,我想轻松地做到这一点。我不想备份整个表,因为我只需要恢复一些已删除的行。

a_h*_*ame 6

您可以使用pg_dump--inserts选项。您还应该检查 SQL 客户端的手册。有些可以将数据导出为INSERT语句。

另一种选择是将您删除的行复制到新表中:

create table _backup
as
with deleted as (
  delete from the_table 
  where .... --<< put your condition here
  returning *
)
select  *
from deleted;
Run Code Online (Sandbox Code Playgroud)

以上将从中删除行the_table并将所有删除的行复制到表中_backup


Luc*_*ini 5

如果您确实需要使用查询的插入语句:

   select 'INSERT INTO table values ('||bla_integer||', '''||bla_string||''')'
   from thetable; 

   Where bla_string and bla_integer are example columns from thetable...
Run Code Online (Sandbox Code Playgroud)