1) 最简单的形式
SQL 代码
- update customers
- set city_name='北京'
- where customer_id<1000
2) 两表(多表)关联update -- 仅在where子句中的连接
SQL 代码
- 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
- )
- -- 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
- )
4) 上述3)在一些情况下,因为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