2013-02-11 67 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

相关问题