大家好!
  我现有表A,其中字段age为null:
SQL code
   A:
   name   sex    book     age
    郭    男     ORACLE   
    梁    男     MSSQL
    许    女     MYSQLSQL code
   B:
   sex
    name  sex   age
    郭    男     20
    郭    男     22
    梁    男     28
    许    女     18
我想,查出根据A表的name,sex分组,与B表中根据name,sex,age的分组结果通过name,sex关联。更新A表中的age,且如果在B表中有多条(age不同)对应与A表中name,sex一条时,不仅要更新A表中存在记录的age,还要增加一条新的记录,记录中name,sex,book与原记录相同,age为B表中另一条记录的值,结果如下:
SQL code
   A:
   name   sex    book     age
    郭    男     ORACLE    20
    郭    男     ORACLE    22
    梁    男     MSSQL     28
    许    女     MYSQL     18
请问,在存储过程,或SQL中该怎样写,才能实现?

解决方案 »

  1.   

    先update
    再insertupdate a 
    set a.age=(select max(b.age) from b where a.name=b.name and a.sex=b.sex);
    commitinsert into a 
    select b.name,b.sex,b.age
    from b 
    where not exists(select * from a where   a.name=b.name and a.sex=b.sex)
    ;
    commit;
      

  2.   

    先update
    再insertupdate a 
    set a.age=(select max(b.age) from b where a.name=b.name and a.sex=b.sex);
    commitinsert into a 
    select b.name,b.sex,b.age
    from b 
    where not exists(select * from a where   a.name=b.name and a.sex=b.sex and a.age=b.age)
    ;
    commit;