我试图在Postgres中从一个数据库复制整个表到另一个数据库。有什么建议吗?


当前回答

Pg_dump并不总是有效。

假设在两个dbs中有相同的表ddl 你可以从stdout和stdin中破解它,如下所示:

 # grab the list of cols straight from bash

 psql -d "$src_db" -t -c \
 "SELECT column_name 
 FROM information_schema.columns 
 WHERE 1=1 
 AND table_name='"$table_to_copy"'"
 # ^^^ filter autogenerated cols if needed     

 psql -d "$src_db" -c  \
 "copy ( SELECT col_1 , col2 FROM table_to_copy) TO STDOUT" |\
 psql -d "$tgt_db" -c "\copy table_to_copy (col_1 , col2) FROM STDIN"

其他回答

以下是对我有效的方法。 第一次转储到一个文件:

pg_dump -h localhost -U myuser -C -t my_table -d first_db>/tmp/table_dump

然后加载转储文件:

psql -U myuser -d second_db</tmp/table_dump

要在本地设置中将一个表从数据库a移动到数据库B,使用以下命令:

pg_dump -h localhost -U owner-name -p 5432 -C -t table-name database1 | psql -U owner-name -h localhost -p 5432 database2

如果你想将数据从一个服务器数据库复制到另一个服务器数据库,那么你必须创建dblink连接两个数据库,否则你可以导出CSV中的表数据,并导入其他数据库表中的数据,表字段应该与主表相同。

使用dblink会更方便!

truncate table tableA;

insert into tableA
select *
from dblink('hostaddr=xxx.xxx.xxx.xxx dbname=mydb user=postgres',
            'select a,b from tableA')
       as t1(a text,b text);

必须使用DbLink将一个表数据复制到不同数据库中的另一个表中。 您必须安装和配置DbLink扩展才能执行跨数据库查询。

我已经在这个话题上创建了详细的帖子。 请访问此链接