我有两张表t1(a,b,c),t2(d,e,f),结构一样,t1表中的c字段不能为null,现需要根据t2表的内容在update  t1中的c字段,我是这样写的:update t1 a set a.c=(select b.f  from t2 b where a.a=b.d and a.b=b.e and a.c=b.f),但在执行过程中,会提示“值不
能为null”,就是在t2表中可能没有符合条件的记录。我想判断一下,如果有数据就更新,没有就保持t1表中的c字段值不变,请教大家
这个sql改怎么写啊,谢谢大家!

解决方案 »

  1.   

    update t1 a 
       set a.c=(select b.f  from t2 b where a.a=b.d and a.b=b.e and a.c=b.f and b.f is not null)
      

  2.   

    --CSDN排版总是出错啊。update t1 a 
       set a.c=(select b.f  from t2 b where a.a=b.d and a.b=b.e and a.c=b.f and b.f is not null
      

  3.   

    update t1 a 
       set a.c=(select b.f  from t2 b where a.a=b.d and a.b=b.e and a.c=b.f and b.f is not null
    --补充,应该加上where条件限制,否则所有的记录都被更新了
     where exists(select 1 from t2 b where a.a=b.d and a.b=b.e and a.c=b.f );
      

  4.   

    如下:update t1 a 
    set a.c=(select b.f from t2 b where a.a=b.d and a.b=b.e and a.c=b.f)
    where exists (select 1 from t2 b where a.a=b.d and a.b=b.e and a.c=b.f)
    关键在exists语句。
      

  5.   

    exists加上是最保险的.有一种情况不用加exists,被更新的表记录数, 大于用来更新的表记录数.
      

  6.   

    最严谨的写法,应该下面这样:update t1 a 
      set a.c=(select b.f  from t2 b where a.a=b.d and a.b=b.e and a.c=b.f and b.f is not null 
    where exists(select 1 from t2 b where a.a=b.d and a.b=b.e and a.c=b.f and b.f is not null); 
      

  7.   


    update t1 a set a.c=(select b.f  from t2 b where a.a=b.d and a.b=b.e and a.c=b.f)
    where exists(select 1 from t2 b where a.a=b.d and a.b=b.e and a.c=b.f)
      

  8.   

    楼主都说了:“t1表中的c字段不能为null”。
    使用了“a.c=b.f”,再用“b.f is not null”是多此一举。
      

  9.   

    where a.a=b.d and a.b=b.e and a.c=b.f这都全=啦,还用更新吗?????
      

  10.   


    哈哈,有意思,大家都被楼主迷糊了,他可能要的是这样的效果(如果他的b.f是可空的话):
    update t1 a 
      set a.c=(select b.f  from t2 b where a.a=b.d and a.b=b.e and b.f is not null) 
    where exists(select 1 from t2 b where a.a=b.d and a.b=b.e and b.f is not null); 
      

  11.   

    我觉得这样简洁点:
    update t1 a
    set a.c = NVL((select b.f  from t2 b where a.a=b.d and a.b=b.e and a.c=b.f), a.c);