[Oracle] 多表关联的update和delete

由于Oracle不支持update或delete from语句,因此,Oracle的多表关联update和delete必须借助于子查询,同理,Oracle也不支持同时update或delete多张表,其典型用法如下:

多表关联update

首先,构造测试表和数据如下:
  1. SYS@TEST16> create table testa as select owner,table_name,status from dba_tables;  
  2.   
  3. Table created.  
  4. SYS@TEST16> create table testb as select owner,object_name,status from dba_objects;  
  5.   
  6. Table created.  
1)更新testa表的status=‘VALID’,关联条件为testa.owner=testb.owner and testa.table_name=testb.table_name
  1. update testa a set status='VALID'  
  2. where exists (select 1 from testb b where a.owner=b.owner and a.table_name=b.object_name);  
2)更新testa表的status等于testb表的status,关联条件同上
  1. update testa a   
  2. set a.status=(select b.status from testb b where a.owner=b.owner and a.table_name=b.object_name)  
  3. where exists (select 1 from testb b where a.owner=b.owner and a.table_name=b.object_name);  
这里要注意的是:只有当子查询每次只返回1条或0条数据时,上述语句才能执行成功,如果返回超过1条数据,将会出现如下错误:
[plain]  view plain copy print ?
  1. ORA-01427: single-row subquery returns more than one row  
这时候,你就必须得对子查询里的返回条数进行限定,如rownum=1或distinct等方法。
这里的where exists字句是不可以省略的,否则将update全表!这里要千万小心。
如果查看执行计划,你会发现上述的update语句将扫描testb表两次,如果该表比较大的话,对性能会有影响,如果只想扫描一次的话,可以用如下方法代替:
  1. update testa a  
  2. set a.status=nvl((select b.status from testb b where a.owner=b.owner and a.table_name=b.object_name),a.status);  

update自身列

有时候,可能需要利用自身的值更新自身的列,比如表test的列col1,col2有空格,我们需要trim去除空格,这时候我们就可以利用rowid更新,update语句如下:
[plain]  view plain copy print ?
  1. update test a  
  2. set (col1,col2)=  
  3. (select trim(b.col1),trim(b.col2) from test b  
  4. where  a.rowid=b.rowid)  
  5. where exists  
  6. (select 1 from test b  
  7. where  a.rowid=b.rowid)  

多表关联delete

1)利用in或not in删除数据
  1. delete from testa where table_name   
  2. in (select object_name from testb);  
2)利用exists或not exists删除数据
  1. delete from testb b  
  2. where exists   
  3. (select 1 from testa a where a.owner=b.owner and a.table_name=b.object_name)  
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值