2013-12-12 9 views
1

假設我想從外部sql文件複製新值。這些值代表具有一對多關係的表格,如:books(book_id, title, author_id, subject), author(author_id, name, field, status)ids1開始並遞增。但是在數據庫中已經有數據/值。那麼如何複製新的值,以便他們獲得正確的id值並保持關係?
感謝在PostgreSQL中複製具有一對多關係的外部文件的值

回答

1

一種方法是將新的數據加載到臨時表new_authornew_book,然後插入來自new_author行到author,他們根本不存在,然後從new_book插入到book,使用從IDS新創建的作者記錄。

create temp table new_book(like book); 
create temp table new_author(like author); 

-- load data into new_book and new_author 
\copy new_author from ~/new_author_file 
\copy new_book from ~/new_book_file 

insert into author (name, field, status) 
select name, field, status 
from new_author 
where name not in (select name from author); 

insert into book (title, author_id, subject) 
select b.title, a.author_id, b.subject 
from new_book b 
    join new_author na on b.author_id = na.author_id 
    join author a on na.name = a.name; 

所有這一切都假定author.name是獨一無二的,而且你知道你需要添加的所有書籍。

+0

恐怕'author.name'不是唯一的! – codyLine

+0

有沒有什麼辦法可以通過編程方式知道已經在目標數據庫中的作者與源數據中的作者是否相同(並且應該將書籍遷移到目標數據庫中的原作者)? – babbageclunk

相關問題