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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM