有一表a
 id count
 1   10
 2   20
 3   30
 4   40;现在有表b如下:
id count
2  100
3  110怎么用把表b中id相对应的count 更新到表a中,更新后;
表a为:
id  count
1    10
2    120
3    140
4    40求sql语句,多谢!

解决方案 »

  1.   

    这样?update a set a.count=a.count+nvl((select b.count from b where a.id=b.id),0)
      

  2.   


    create table a (id number(5),count number(10));
    insert into a values (1,10);
    insert into a values (2,20);
    insert into a values (3,30);
    insert into a values (4,40);create table b (id number(5),count number(10));
    insert into b values (2,100);
    insert into b values (3,110);select * from a;     id     count
    ----------------------
    1 1 10
    2 2 20
    3 3 30
    4 4 40update a set count=count+nvl((select b.count from b where a.id=b.id),0);
    --提交select * from a;     id     count
    ----------------------
    1 1 10
    2 2 120
    3 3 140
    4 4 40
      

  3.   

    如果a跟b表一对多的话,二楼的会有问题
    update a
       set a.count = (select sum(count) from b where b.id = a.id)
     where exists (select 1 from b where b.id = a.id);
      

  4.   

    nvl函数在此,无论A 和 B的列数相等与否都不会出现问题。所以二楼貌似更简单多了。
      

  5.   

    我也同意。理由:如果a跟b表一对多的话,会有问题,因为,嵌套语句跟运算符比如等于号连用,只能是单值。以后,嵌套语句和运算符联用需要特别在意这个问题:看看子查询返回的值的个数!!!
    但update a
    set a.count = (select sum(count) from b where b.id = a.id)
    where exists (select 1 from b where b.id = a.id);这条语句貌似无法实现LZ的要求呀??
      

  6.   

    是的,还是你比较仔细,应该加上原来的值
    set a.count = a.count+(select nvl(sum(count),0) from b where b.id = a.id)
    where exists (select 1 from b where b.id = a.id);
      

  7.   

    update a t set t.count=t.count+nvl((select t2.count from b t2 where t.id = t2.id),0)
      

  8.   


    merge into a
    using b
    on (b.id = a.id)
    when matched then
      update set a.count = a.count + b.count这地方没人用merge into 语法吗
      

  9.   

    update a t set t.count=t.count+nvl((select t2.count from b t2 where t.id = t2.id),0)