两个不同结构的数据库之间的数据迁移(Postgresql)

Data Migration Between two databases with different structures (Postgresql)

我有两个数据库,old_db 和 new_db,我想做的是将数据记录从 old_db 转移到 new-db 但具有不同的结构或不同的列.我正在创建一个 sql 脚本,它将 old_db 上传到 new_db,然后我可以从那里获取从 old_db 到 new_db 的数据。

old_db 中的一个表是这样的:

tbl_person:

person_id bigint,

last_name text,

first_name text,

现在我想将数据传输到 new_db 中,结构如下,其中 new_id 列将生成新的 ID 号,而 person_id 将被引用或传输到 ref_id列:

tbl_person:

new_id bigint, ---this column is where the new id will be generated

last_name text,

first_name text,

ref_id bigint; ---this column is where the person_id will be copied

我如何创建一个 sql 脚本,以便从 old_db 到 new_db 正确引用此数据???我不是要工具或 GUI,而是要我将在 shell 脚本中执行的 sql 脚本。我正在使用 postgresql 作为我的 DBMS,所以我还需要有关 pg_dump 或 pg_restore 的帮助,以便在 new_db 中上传 old_db。 TIA.

其根源是直接从旧 table 向新 table 插入数据。注意:我没有运行这个代码。

INSERT INTO new_db.tbl_person (last_name, first_name, ref_id)
(SELECT last_name, first_name, person_id FROM old_db.tbl_person)

如果两个数据库 运行 在同一个 Postgres 实例中,这将独立运行。如果它们在彼此可见的主机上的不同实例中,您可以使用 dblink,这使得 SELECT 查询类似于:

SELECT * FROM
dblink(
  'host=otherhost user=me password=pass dbname=old_db',
  'SELECT last_name, first_name, person_id FROM tbl_person'
) AS tbl_old_person(last_name text, first_name test, person_id integer)

如果主持人看不到对方,pg_dumppg_restore 上有很多关于 Whosebug 的帮助:

  • Using pg_dump to only get insert statements from one table within database
  • Restore a postgres backup file using the command line?