数据库中有两个表,表1如下:
CREATE TABLE Table1
(
 ID1 INTEGER, 
 AAA NUMBER, 
 BBB NUMBER, 
 CCC NUMBER, 
 DDD NUMBER,   
);其中ID1和AAA为联合主键
表2:
CREATE TABLE Table2
(
 ID2 INTEGER,
 AAA NUMBER,
 BBB2 NUMBER,  
);其中ID2和AAA为联合主键
想把表2中的BBB2字段的数据(许多行)分别放入表1中的BBB、CCC字段中,当表1和表2中的联合主键相同时用下面语句:
insert into table (ID1, AAA, BBB) select ID2, AAA, BBB2 from table2 on duplicate key update BBB = values(BBB2);
insert into table (ID1, AAA, CCC) select ID2, AAA, BBB2 from table2 on duplicate key update CCC = values(BBB2);
怎么老是提示命令未正确结束?请高手帮忙解答下,谢了

解决方案 »

  1.   

    --如果是10g或是以上版本的话可以用merge into
    merge into table1
    using table2
    on(table1.id1=table2.id2 and table1.aaa=table2.aaa)
    when matched then
    update
    set table1.bbb=table2.bbb2 ,table1.ccc=table2.ccc;
    when not matched then
    insert
    values(table2.id2,table2.bbb2);
      

  2.   

    肯定会违反唯一性约束的,因为你往table1插入数据,主键是  (ID1,AAA) 两条插入的数据联合主键是一样的,肯定不行
      

  3.   

    update table1 t1 set (t1.bbb,t1.ccc)=(select t2.bbb2,t2.bbb2 from table2 t2 where (t2.id2=t1.id1 and t2.aaa=t2.aaa) where t1.id1=t2.id2 and t1.aaa=t2.aaa;
      

  4.   

    --这样试试
    update table1 set bbb=(select bbb2 from table2 
                           where table1.id=table2.id and table1.aaa=table2.aaa)
    where exists(select null from table2 
                 where table1.id=table2.id and table1.aaa=table2.aaa)
      

  5.   

    这个可以,能否解释下这个很长的句子中用两个where的原因以及exist的作用。
    小弟刚入门,还请多指教!
      

  6.   


    update table1 a set (a.bbb,a.ccc)=(select b.bbb2,b.bbb2 from table2 b where b.id2=a.id1 and b.aaa=a.aaa)
    where exists 
    (select 1 from table2 c
    where a.id1=c.id2 and a.aaa=c.aaa)
      

  7.   

    update table1 set bbb=(select bbb2 from table2 
                           where table1.id=table2.id and table1.aaa=table2.aaa)
    --这个是更新数据用的where exists(select null from table2 
                 where table1.id=table2.id and table1.aaa=table2.aaa)
    --如果没有这个 那
    些table1表中不符合where table1.id=table2.id and table1.aaa=table2.aaa这个条件的语句将会被更新为null
    你可以测试下