Copy results from a PostgreSQL view in one DB to a table in another

流过昼夜 提交于 2019-12-10 15:22:06

问题


Complete PostgreSQL newb.

I have 7-8 views worth of data in db1 that I need to copy into tables with a matching schemae (schemas?) in a different database, db2. The destination database may be the same instance of PostgreSQL, or one on a different box altogether.

I know 2-3 different ways to accomplish this with the databases I'm familiar with, but I'm helpless on this one. Can someone suggest some basic strategies for me?

In a perfect world, I'd prefer not to have to do anything that feels too ETL-ish - I'd rather do some sort of

SELECT FROM instance1.db1.viewname INTO instance2.db5.tablename

then dump data out of the view as text file and reload into the destination table.

Since I don't know PostgreSQL, I don't really know what is within the realm of possibility, though.


回答1:


You do not need to create a temporary table for COPY TO. Any query can be the source since PostgreSQL 8.2.

COPY (SELECT * FROM view1) TO '/var/lib/postgres/myfile1.csv';

Read the manual about COPY. Create the needed tables locally with

CREATE table tbl1 AS
SELECT * FROM view1
LIMIT 0;   -- no data, just the schema.

Copy the DDL instructions and create all tables in the target db. pgAdmin is one convenient GUI to do that with. Delete the empty tables in the source db again. Load data with

COPY tbl1 FROM '/var/lib/postgres/myfile1.csv';

Dump / restore like @wildplasser describes it, is another way.

For a one time transfer one of those methods is advisable. For repeated application, dblink or SQL/MED (Management of External Data) may be more suitable.




回答2:


CREATE TEMPORARY TABLE mytmp
AS SELECT * from myview
WHERE 1=1
;


COPY mytmp TO '/tmp/test.csv'
;

An even better method is to:

  • copy the views into tables (create table1 as select * from view1; ...)
  • use pg_dump -t table1 -t table2 ... mydbname >myfile.out
  • use myfile.out to recreate and fill the tables.


来源:https://stackoverflow.com/questions/8022061/copy-results-from-a-postgresql-view-in-one-db-to-a-table-in-another

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!