zoukankan      html  css  js  c++  java
  • Oracle :多表更新多个字段

    https://blog.csdn.net/funnyfu0101/article/details/52765235

    总体原则:1)更新的时候一定要加where条件,否则必然引起该字段的所有记录更新

                       2)跨表更新时,set和where时,尽量减少扫描次数,从而提高优化

    update更新实例:

    1) 最简单的形式-单表更新

    SQL 代码
    1. --经确认customers表中所有customer_id小于1000均为'北京'
    2. --1000以内的均是公司走向全国之前的本城市的老客户:)
    3. update customers
    4. set city_name='北京'
    5. where customer_id<1000

    2) 两表(多表)关联update -- set为简单的数据(直接是值),且仅在where字句中的连接

    SQL 代码
    1. --这次提取的数据都是VIP,且包括新增的,所以顺便更新客户类别
    2. update customers a -- 使用别名
    3. set customer_type='01' --01 为vip,00为普通
    4. where exists (select 1
    5. from tmp_cust_city b
    6. where b.customer_id=a.customer_id
    7. )

    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. 优化:单个字段的优化,简化为扫描一遍
      7.1 SQL 代码
      1. update customers a -- 使用别名
      2. set city_name=nvl((select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id),a.city_name)
    8. -- update 超过2个值(字段
    9. update customers a -- 使用别名
    10. set (city_name,customer_type)=(select b.city_name,b.customer_type
    11. from tmp_cust_city b
    12. where b.customer_id=a.customer_id)
    13. where exists (select 1
    14. from tmp_cust_city b
    15. where b.customer_id=a.customer_id
    16. )

    3的缺点,就是对表B进行两遍扫描;

    4) 特殊情况的优化:

    因为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


    这样能避免对B表或其索引的2次扫描,但前提是 A(customer_id) b(customer_id)必需是unique index或primary key

  • 相关阅读:
    Vmware Vsphere WebService之vijava 开发一-vcenter连接、及集群信息获取
    Vmware Vsphere WebService SDK开发(第一讲)-基本知识学习
    RabbitMQ安装以及java使用(二)
    redis单机安装以及集群搭建(redis-6.2.6)
    Spring Cloud Gateway中Filter获取Request Body的几种方式
    电子发票插入微信卡包之PDF上传
    Elasticsearch集群搭建详解
    微服务的设计原则
    centos 7.4 64位 mysql的安装
    RabbitMQ安装以及java使用(一)
  • 原文地址:https://www.cnblogs.com/Nina-piaoye/p/9855681.html
Copyright © 2011-2022 走看看