程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 數據庫知識 >> Oracle數據庫 >> Oracle數據庫基礎 >> ORACLE UPDATE 語句語法與性能分析的一點看法

ORACLE UPDATE 語句語法與性能分析的一點看法

編輯:Oracle數據庫基礎

為了方便起見,建立了以下簡單模型,和構造了部分測試數據:
在某個業務受理子系統BSS中,
--客戶資料表
create table customers
(
customer_id number(8) not null, -- 客戶標示
city_name varchar2(10) not null, -- 所在城市
customer_type char(2) not null, -- 客戶類型
...
)
create unique index PK_customers on customers (customer_id)
由於某些原因,客戶所在城市這個信息並不什麼准確,但是在
客戶服務部的CRM子系統中,通過主動服務獲取了部分客戶20%的所在
城市等准確信息,於是你將該部分信息提取至一張臨時表中:
create table tmp_cust_city
(
customer_id number(8) not null,
citye_name varchar2(10) not null,
customer_type char(2) not null
)
1) 最簡單的形式
--經確認customers表中所有customer_id小於1000均為'北京'
--1000以內的均是公司走向全國之前的本城市的老客戶:)
update customers
set city_name='北京'
where customer_id<1000
2) 兩表(多表)關聯update -- 僅在where字句中的連接
--這次提取的數據都是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 -- 被修改值由另一個表運算而來
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
)
-- 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
)
注意在這個語句中,
=(select b.city_name,b.customer_type
from tmp_cust_city b
where b.customer_id=a.customer_id
)

(select 1
from tmp_cust_city b
where b.customer_id=a.customer_id
)
是兩個獨立的子查詢,查看執行計劃可知,對b表/索引掃描了2篇;
如果捨棄where條件,則默認對A表進行全表
更新,但由於(select b.city_name from tmp_cust_city b where where b.customer_id=a.customer_id)
有可能不能提供"足夠多"值,因為tmp_cust_city只是一部分客戶的信息,
所以報錯(如果指定的列--city_name可以為NULL則另當別論):

01407, 00000, "cannot update (%s) to NULL"
// *Cause:
// *Action:
一個替代的方法可以采用:
update customers a -- 使用別名
set city_name=nvl((select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id),

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved