2015-07-04 55 views
3

我有兩個數據庫old_db和new_db,我想要做的是將數據記錄從old_db傳輸到new-db,但具有不同的結構或不同的列。我正在創建一個sql腳本,它將old_db上傳到new_db,然後從那裏我可以將old_db的數據傳遞給new_db。不同結構的兩個數據庫之間的數據遷移(Postgresql)

一個在old_db的表是這樣的:

tbl_person:

person_id bigint, 

last_name text, 

first_name text, 

現在我想將數據傳輸到new_db,像這樣的結構,其中NEW_ID列將產生新的ID號和的爲person_id將被引用或tranferred到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。

+0

現在這個問題太籠統了。你能否提供一些你真正想要做的新舊參考的真實例子。我會用「舊」和「新」引用來查看「視圖」,並使用這些「視圖」來替換「舊」表? –

+0

示例:old_db(person_id,last_name,first_name)values(1234,Smith,John)|現在我想以這種方式將這些數據移動到new_db中,並且person_id將被移動到ref_id列中,如下所示:new_db(new_id,last_name,first_name,ref_id)values(1,Smith,John, 1234)我將如何做到這一點? @Ryan –

回答

0

這個的根源將直接從舊錶中插入數據到新表中。注意:我沒有運行這個代碼。

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) 

如果主機無法看到對方,有很多的幫助周圍的StackOverflow上pg_dumppg_restore

+0

謝謝。但我所做的是將old_db上傳到new_db。我想知道如何使用UPDATE查詢將我的old_db表中的數據更新到new_db表。 @Kristjan –

+0

這聽起來像你可能實際上正在尋找[ALTER TABLE](http://www.postgresql.org/docs/9.4/static/sql-altertable.html)。 –

相關問題