从两个tables, table1和table2拿记录,insert进另一个table.简单写法是,
insert into table3 select a1,a2,a3,a4 from table1 a, table2 b where a.id=b.id但是又存在另一个问题,在insert table3的时候,如果和a1,a2,a3全部相等的记录已经有了,就不要insert了。
这样可不可以写成一句sql?
或者要怎样,可以完成这个任务?

解决方案 »

  1.   

    insert into table3 
    select a1,a2,a3,a4
     from table1 a, table2 b , table3 cwhere
     a.id=b.id 
    and not exists(c.字段=a.的字段)
      

  2.   

    先看这个select吧,我按说的用not exists,但是好像很慢,半小时了,结果还没有出来,因为实际上的这个sql要更复杂一些,prototype是这样的,select a.a1,a.a2,a.a3,a.a4,b.b1,c.c1 from
    a, b, c,d
    where a.a4 in 
    (
    select max(x.a4) from a x, c y where
    X.a1 = Y.a1 
            AND X.a2 = Y.a2 
            AND X.a3 = Y.a3
            and X.a5='T'
            and Y.c2 = 'TI'
            GROUP BY X.a1, X.a2, X.a3
    )
    AND a.a1 = c.a1
    AND a.a2 = c.a2
    AND a.a3 = c.a3
    AND a.a4 = b.b2
    and a.a5='T'
    and c.c2 = 'TI'
    AND not exists(a.a1 = d.d1
                   and a.a2 = d.d2
                   and a.a3 = d.d3)首先这个sql对不对,其次怎么写可以执行快一点呢?
      

  3.   

    insert into table3
    (
       select a1,a2,a3,a4 
       from table1 a 
       where (a1,a2,a3) not in(select a1,a2,a3 from table3)
    )
      

  4.   

    本菜鸟听一个高手说过有一个sql关键字是执行有就更新没有就插入的功能
    当本菜鸟没有找到,(呵呵)
      

  5.   

    多谢gaohaha,试下来你的sql比较适合我的情况。速度可以接受。
      

  6.   

    有一个sql关键字是执行有就更新没有就插入的功能 有这样的?
      

  7.   

    试下这个:merge into table3 t3
    using 
    (select a.a1 a1,a.a2 a2,a.a3 a3,a.a4 a4 from table1 a inner join table2 b on a.id=b.id) t1
    on(t3.a1=t1.a1 and t3.a2=t1.a2 and t3.a3=t1.a3)
    when not matched then
    insert (t3.a1,t3.a2,t3.a3,t3.a4) values(t1.a1,t1.a2,t1.a3,t1.a4)
      

  8.   

    merge就是insert&update, 数据量很大的时候exits比in好