oracle資料庫 update更新多表總結

2021-07-23 12:50:12 字數 2862 閱讀 7249

總體原則: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

Oracle資料庫update觸發器

在專案中使用到oracle資料庫的update觸發器,先記錄下來方便以後查閱。預備知識和格式以後再編輯吧,先把內容貼出來。create or replace trigger demo trigger after update on tb goods referencing new as new ol...

資料庫update死鎖

比較常見的死鎖場景,併發批量update時的乙個場景 update cross marketing set gmtmodified now pageview pageview extpageview where marketingid marketingid 第一次呼叫時,marketingid傳入...

資料庫學習 update(批量更新)

資料更新update命令 用指定要求的值更新指定表中滿足天劍的資料的指定列的值 語法形式 update 表名 set 列名 表示式 子查詢 列名 表示式 子查詢 where 條件表示式 示例 1 將所有教師工資上調 10 原表資料 執行兩次後結果 2 將所有計算機學院的老師工資上調 10 updat...