需求
有t1,t2兩張表,通過A字段關(guān)聯(lián),現(xiàn)在需要在t1表新增字段B,將t2表中的字段C更新到t1表新增的字段B中。t1表數(shù)據(jù)一千二百萬,t2表數(shù)據(jù)七百萬。
常規(guī)方法
直接使用update來更新字段。
--t1表新增字段B
alter table t1 add ( B varchar2(32));
--將t2表的字段C更新到t1表的B列中
update t1 set B = (select C from t2 where t1.A = t2.A);
在數(shù)據(jù)量較少的時候,這種寫法其實是沒問題的,簡潔易懂。但是數(shù)據(jù)量太大的情況則不適用,在測試環(huán)境實際跑了一下,一個小時都沒更新完,遂放棄。
使用MERGE
merge into是oracle內(nèi)置函數(shù),通常用來處理insertOrUpdate的需求,如果存在數(shù)據(jù)就update,如果不存在就insert。也可以只用來更新,速度很快。
--t1表新增字段B
alter table t1 add ( B varchar2(32));
--通過merger的方式,將B表的column3字段更新到A表的column2列中
merge into t1 Using (select * from t1 ) on (t1.A = t2.A)
when matched then update set t1.B = t2.C
通過這種方式,在測試環(huán)境實際跑下來十分鐘左右可以更新完成。
merge into的詳細用法可以參考這篇文章:
Oracle中merge into的使用
使用CTAS
create table as 的方式在之前的使用中,多用于創(chuàng)建備份表。因為這次需求才認識到其更多的用法。性能十分強悍。
--首先使用ctas的方式創(chuàng)建臨時表
create table temp_A as select t1.*,t2.C from t1 left join t2 on t1.A = t2.A;
--刪除原始表
drop table A;
--將臨時表重名稱
rename temp_A to A;
--重新創(chuàng)建原表的索引等。。。
create index ......
測試環(huán)境執(zhí)行下來,一分鐘左右可以執(zhí)行完成。
CTAS的更多用法,可以參考Oracle官網(wǎng)的如下內(nèi)容:
How to Update millions or records in a table
這一段內(nèi)容信息量非常大,值得仔細品讀。