https://blog.csdn.net/funnyfu0101/article/details/52765235
總體原則:1)更新的時候一定要加where條件,否則必然引起該字段的所有記錄更新
2)跨表更新時,set和where時,盡量減少掃描次數,從而提高優化
update更新實例:
1) 最簡單的形式-單表更新
SQL 代碼
- --經確認customers表中所有customer_id小於1000均為'北京'
- --1000以內的均是公司走向全國之前的本城市的老客戶:)
- update customers
- set city_name='北京'
- where customer_id<1000
2) 兩表(多表)關聯update -- set為簡單的數據(直接是值),且僅在where字句中的連接
SQL 代碼
- --這次提取的數據都是VIP,且包括新增的,所以順便更新客戶類別
- update customers a -- 使用別名
- set customer_type='01' --01 為vip,00為普通
- where exists (select 1
- from tmp_cust_city b
- where b.customer_id=a.customer_id
- )
3) 兩表(多表)關聯update -- 被修改值由另一個表運算而來
SQL 代碼
- update customers a -- 使用別名
- set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)
- where exists (select 1
- from tmp_cust_city b
- where b.customer_id=a.customer_id
- )
- 優化:單個字段的優化,簡化為掃描一遍
7.1 SQL 代碼
- update customers a -- 使用別名
- set city_name=nvl((select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id),a.city_name)
- -- update 超過2個值(字段)
- update customers a -- 使用別名
- set (city_name,customer_type)=(select b.city_name,b.customer_type
- from tmp_cust_city b
- where b.customer_id=a.customer_id)
- where exists (select 1
- from tmp_cust_city b
- where b.customer_id=a.customer_id
- )
3的缺點,就是對表B進行兩遍掃描;
4) 特殊情況的優化:
因為B表的紀錄只有A表的20-30%的紀錄數,且
A表使用INDEX的情況
使用cursor也許會比關聯update帶來更好的性能:
SQL 代碼
- set serveroutput on
- declare
- cursor city_cur is
- select customer_id,city_name
- from tmp_cust_city
- order by customer_id;
- begin
- for my_cur in city_cur loop
- update customers
- set city_name=my_cur.city_name
- where customer_id=my_cur.customer_id;
- /** 此處也可以單條/分批次提交,避免鎖表情況 **/
- -- if mod(city_cur%rowcount,10000)=0 then
- -- dbms_output.put_line('----');
- -- commit;
- -- end if;
- end loop;
- end;
5) 關聯update的一個特例以及性能再探討
在oracle的update語句語法中,除了可以update表之外,也可以是視圖,所以有以下1個特例:
SQL 代碼
- update (select a.city_name,b.city_name as new_name
- from customers a,
- tmp_cust_city b
- where b.customer_id=a.customer_id
- )
- set city_name=new_name
這樣能避免對B表或其索引的2次掃描,但前提是 A(customer_id) b(customer_id)必需是unique index或primary key