ORACLE多表关联UPDATE 语句
GPS平臺、網站建設、軟件開發、系統運維,找森大網絡科技!
https://cnsendnet.taobao.com
來自森大科技官方博客
http://www.cnsendblog.com/index.php/?p=1197
為了方便起見,建立了以下簡單模型,和構造了部分測試數據:
在某個業務受理子系統BSS中,
由于某些原因,客戶所在城市這個信息并不什么準確,但是在
客戶服務部的CRM子系統中,通過主動服務獲取了部分客戶20%的所在
城市等準確信息,于是你將該部分信息提取至一張臨時表中:
注意在這個語句中,
=(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表進行全表
更新,但由于
有可能不能提供"足夠多"值,因為tmp_cust_city只是一部分客戶的信息,所以報錯(如果指定的列–city_name可以為NULL則另當別論):
1.01407, 00000, "cannot update (%s) to NULL" 2. // *Cause: 3. // *Action:一個替代的方法可以采用:
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)或者
1.set city_name=nvl((select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id),'未知')– 當然這不符合業務邏輯了
考慮A表使用INDEX的情況,使用cursor也許會比關聯update帶來更好的性能:
在oracle的update語句語法中,除了可以update表之外,也可以是視圖,所以有以下1個特例:
這樣能避免對B表或其索引的2次掃描,但前提是 A(customer_id) b(customer_id)必需是unique index或primary key。否則報錯:
1.01779, 00000, "cannot modify a column which maps to a non key-preserved table" 2. // *Cause: An attempt was made to insert or update columns of a join view which 3. // map to a non-key-preserved table. 4. // *Action: Modify the underlying base tables directly.6)oracle另一個常見錯誤
回到3)情況,由于某些原因,tmp_cust_city customer_id 不是唯一index/primary key
當對于一個給定的a.customer_id
(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)
返回多余1條的情況,則會報如下錯誤:
一個比較簡單近似于不負責任的做法是
1.update customers a -- 使用別名 2.set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id and rownum=1)如何理解 01427 錯誤,在一個很復雜的多表連接update的語句,經常因考慮不周,出現這個錯誤,
仍已上述例子來描述,一個比較簡便的方法就是將A表代入 值表達式 中,使用group by 和
having 字句查看重復的紀錄
GPS平臺、網站建設、軟件開發、系統運維,找森大網絡科技!
https://cnsendnet.taobao.com
來自森大科技官方博客
http://www.cnsendblog.com/index.php/?p=1197
總結
以上是生活随笔為你收集整理的ORACLE多表关联UPDATE 语句的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 干货分享好用的绘图工具
- 下一篇: 推荐8个实用精美的在线网站,珍藏多年!