oracle 多表关联 update

1) 最简单的形式

SQL 代码
  1. update customers
  2. set city_name='北京'
  3. where customer_id<1000

2) 两表(多表)关联update -- 仅在where子句中的连接

SQL 代码
  1. update customers a -- 使用别名
  2. set customer_type='01' --01 为vip,00为普通
  3. where exists (select 1
  4. from tmp_cust_city b
  5. where b.customer_id=a.customer_id
  6. )

3) 两表(多表)关联update -- 被修改值由另一个表运算而来

SQL 代码
  1. update customers a -- 使用别名
  2. set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)
  3. where exists (select 1
  4. from tmp_cust_city b
  5. where b.customer_id=a.customer_id
  6. )
  7. -- update 超过2个值
  8. update customers a -- 使用别名
  9. set (city_name,customer_type)=(select b.city_name,b.customer_type
  10. from tmp_cust_city b
  11. where b.customer_id=a.customer_id)
  12. where exists (select 1
  13. from tmp_cust_city b
  14. where b.customer_id=a.customer_id
  15. )

4) 上述3)在一些情况下,因为B表的纪录只有A表的20-30%的纪录数,
考虑A表使用INDEX的情况,使用
cursor也许会比关联update带来更好的性能:

SQL 代码
  1. set serveroutput on
  2. declare
  3. cursor city_cur is
  4. select customer_id,city_name
  5. from tmp_cust_city
  6. order by customer_id;
  7. begin
  8. for my_cur in city_cur loop
  9. update customers
  10. set city_name=my_cur.city_name
  11. where customer_id=my_cur.customer_id;
  12. /** 此处也可以单条/分批次提交,避免锁表情况 **/
  13. -- if mod(city_cur%rowcount,10000)=0 then
  14. -- dbms_output.put_line('----');
  15. -- commit;
  16. -- end if;
  17. end loop;
  18. end;

5) 关联update的一个特例以及性能再探讨
在oracle的
update语句语法中,除了可以update表之外,也可以是视图,所以有以下1个特例:

SQL 代码
  1. update (select a.city_name,b.city_name as new_name
  2. from customers a,
  3. tmp_cust_city b
  4. where b.customer_id=a.customer_id
  5. )
  6. set city_name=new_name


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值