zoukankan      html  css  js  c++  java
  • Oracle中用一个表更新另一个表(转)

    http://soft.chinabyte.com/database/48/12342048.shtml

    Oracle中用一个表更新另一个表

    发布时间:2012-05-25 00:00:00 来源:中国IT实验室 作者:佚名
     
    关键字:Oracle
     

      Oracle中用一个表的数据更新另一个表的数据

      有下面两个表:将表tab1中id值与和表tab2中id值相同的行的val更新为tab2中val的值。

      select * from tab1;

      select * from tab2

      最容易犯的错误是:update tab1 set val=(select val from tab2 where tab1.id=tab2.id);

      更新完后的结果是:select * from tab1,在tab1中有的行,如果在tab2中没有对应的行,

      值被更新为null

      改正为:update tab1 set val=(select val from tab2 where tab1.id=tab2.id)

      where exists (select 1 from tab2 where tab1.id=tab2.id)

      但是如果tab2中有多条对应tab1中一条的情况也会出错。

      最好的方法是用merge语法:

      [sql]

      merge into tab1

      using tab2

      on(tab1.id=tab2.id)

      when matched then

      update set tab1.val = tab2.val

      同样,如果tab2中有多条对应tab1中一条的情况也会出错:ORA-30926:

      unable to get a stable set of rows in the source tables

      比如在tab2中再插入一条 insert into tab2 values(2,'xxxx')

      可以通过在using中的subquery中将重复记录过滤来避免这种错误,merge终极版:

      [sql]

      merge into tab1

      using (select * FROM tab2 X WHERE X.ROWID =

      (SELECT MAX(Y.ROWID) FROM tab2 Y WHERE X.ID = Y.ID)) tab2

      on(tab1.id=tab2.id)

      when matched then

      update set tab1.val = tab2.val

  • 相关阅读:
    python中的基础坑
    Django组件content-type使用方法详解
    数据库范式
    MySQL常见面试题索引、表设计
    python操作MySQL之pymysql模块
    MySQL备份与还原
    MySQL查询缓存
    MySQL索引及查询优化
    MySQL事务隔离之MVCC版本控制
    MySQL事务及实现、隔离级别及锁与优化
  • 原文地址:https://www.cnblogs.com/gongyu/p/4527231.html
Copyright © 2011-2022 走看看