两张表A,B有相同的列(id,grade),我想对那些有相同id的数据,把A的grade更新为B的grade.
简单来说我想运行以下语句(当然,这是错误的用法):
update A set A.grade=B.grade
where A.id=B.id
我想请教一下这样的sql该怎么写?

解决方案 »

  1.   

    update a set a.gread=(select b.gread from b where b.id=a.id)
      

  2.   

     update a
        set a.grade =
            (select b.grade from b where a.id = b.id)
            --加上下面限制条件,(不加限制,如果没有匹配到B表ID,GRADE值会被更新为null)
      where exists (select 1 from b where a.id = b.id);或者merge into 
    merge into a
    using b
    on (a.id = b. id)
    when matched then
      update set a.grade = b.grade
      

  3.   

    update a
      set a.grade = (select b.grade from b where b.id = a.id);
      

  4.   

    不带where子句的update语句一定会对a表的grade列的每个值进行更新,当找到与b表匹配的记录能够正确更新,但是当找不与之匹配的记录时,无法判断应该赋予的内容,会将其置为NULL!所以下面更新比较好,前提是表中的id没有重复update a set a.gread= (select b.gread from b where b.id=a.id) where id in ( select id from b);
      

  5.   


    2# 的第二个语句,10g 以上可用(含 10g),在9i 版本,必须要写上 matched 和  not matched 这两个,10 g 以上,只写 matched 就可以了;