2013-02-11 65 views
1

我有兩個表,即PERSON和妻子。我想讓WIFE的數據在PERSON表格中可用,同時保持WIFE的條目保持不變,同時將PERSON的值與妻子的數據相加。
從一個表將數據複製到甲骨文另一人

Person表

PK NAME  ADDRESS IS_MARRIED 
    1 John  ab city  Y   
    2 Varvatos cd town  N 
    3 Smith  ef town  Y 
    4 Henry  gh city  Y 
    5 Lynda  gh city  Y 

WIFE表

PK PERSON_ID (FK) NAME   
    1 1     Alice 
    2 3     Rosy 
    3 4     Lynda 

現在我想WIFE表的數據複製到PERSON表這樣
PERSON表

PK NAME  ADDRESS IS_MARRIED 
    1 John  ab city  Y   
    2 Varvatos cd town  N 
    3 Smith  ef town  Y 
    4 Henry  gh city  Y 
    5 Lynda  gh city  Y 
    6 Alice  ab city  Y 
    7 Rosy  ef town  Y 

正如在給出的例子中,您可能已經注意到,妻子的地址與她的配偶相同,並且與IS_MARRIED列相同。而且,PK也沒有重複。如何去做這件事?
*編輯*
另一個重要因素是琳達已經存在於PERSON表,因此,我當然不希望重複她的條目。

回答

2
declare 
newId number; 
begin 
select nvl(max(person.pk),0) + 1 into newId from person; 
for x in (
    select w.Name, p.Address 
    from wife w inner join Person p 
    on w.Person_id = P.pk) loop 
    insert into Person(pk, Name,Address,Is_Married) values (newId ,x.Name ,x.Address,'Y'); 
    newId := newId +1; 
end loop; 
commit; 
end 
0

試試這個:

insert into Person(Name, Address, Is_Married) 
    select w.name, p.address, 'Y' 
    from wife w left outer join 
     Person p 
     on w.Person_id = person.pk 
+0

我想,它應該'右外join'代替''Y'',它應該是'p.is_married'也'情況下w.name爲null,則p.name end' – 2013-02-11 17:22:51

+0

@Gordon Linoff什麼主鍵? – 2013-02-11 17:24:33

+0

不要觸摸主鍵,它只是爲了加入。 – 2013-02-11 17:26:31

1

使用CTAS創建表的表名作爲選擇任何你從兩個表需要。只需編寫一個連接,然後將create table添加爲...在select關鍵字之上。如果你喜歡插入在戈登的例子,你的表是很大的,那麼你可以加一個附加提示您插入...

0

你好,請嘗試下面的代碼:這滿足您的需求量的

declare PKId number; 
begin 
    select nvl(max(person.pk),0) + 1 into PKId 
    from person; 

    for x in (select w.Name, p.Address 
      from wife w 
      inner join Person p on w.Person_id = P.pk 
      ) loop 

    insert into Person(pk, Name,Address,Is_Married) 
    values (PKId ,x.Name ,x.Address,'Y'); 

    PKId := PKId +1; 
    end loop; 
    commit; 
end 
+0

我最後的回答和你的回答有什麼不同嗎? – 2013-02-12 11:45:26

相關問題