---
title: "update更新多表总结"
author: "paynexss"
date: "2017-04-01T16:06:55Z"
tags: ["Oracle"]
categories: ["数据库"]
slug: "update"
draft: false
lastmod: "2017-04-01T16:06:55Z"
id: 2367047
url: "https://paynexss.iteye.com/blog/2367047"
---

**总体原则：1）更新的时候一定要加where条件，否则必然引起该字段的所有记录更新**

                   **2）跨表更新时，set和where时，尽量减少扫描次数，从而提高优化**

 

**update更新实例：**

 

1\) 最简单的形式-单表更新

SQL 代码

1. --经确认customers表中所有customer\_id小于1000均为'北京'
2. --1000以内的均是公司走向全国之前的本城市的老客户:)
3. update customers
4. set city\_name='北京'
5. where customer\_id&lt;1000

2\) 两表(多表)关联update -- set为简单的数据（直接是值），且仅在where字句中的连接

SQL 代码

1. --这次提取的数据都是VIP，且包括新增的,所以顺便更新客户类别
2. update customers a -- 使用别名
3. set customer\_type='01' --01 为vip，00为普通
4. where exists (select 1
5. from tmp\_cust\_city b
6. where b.customer\_id=a.customer\_id
7. )

 

3\) 两表(多表)关联update -- 被修改值由另一个表运算而来

SQL 代码

01. update customers a -- 使用别名
02. set city\_name=(select b.city\_name from tmp\_cust\_city b where b.customer\_id=a.customer\_id)
03. where exists (select 1
04. from tmp\_cust\_city b
05. where b.customer\_id=a.customer\_id
06. )
07. 优化：单个字段的优化，简化为扫描一遍
    
    7.1 SQL 代码
    
    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)
08. -- update 超过2个值（字段）
09. update customers a -- 使用别名
10. set (city\_name,customer\_type)=(select b.city\_name,b.customer\_type
11. from tmp\_cust\_city b
12. where b.customer\_id=a.customer\_id)
13. where exists (select 1
14. from tmp\_cust\_city b
15. where b.customer\_id=a.customer\_id
16. )

3的缺点，就是对表B进行两遍扫描；

 

 

 

4\) 特殊情况的优化：

因为B表的纪录只有A表的20-30%的纪录数，且

 

A表使用INDEX的情况

 

 

使用cursor也许会比关联update带来更好的性能：

 

 

 

SQL 代码

01. set serveroutput on
02. declare
03. cursor city\_cur is
04. select customer\_id,city\_name
05. from tmp\_cust\_city
06. order by customer\_id;
07. begin
08. for my\_cur in city\_cur loop
09. update customers
10. set city\_name=my\_cur.city\_name
11. where customer\_id=my\_cur.customer\_id;
12. /\** 此处也可以单条/分批次提交，避免锁表情况 \*\*/
13. -- if mod(city\_cur%rowcount,10000)=0 then
14. -- dbms\_output.put\_line('----');
15. -- commit;
16. -- end if;
17. end loop;
18. end;

5\) 关联update的一个特例以及性能再探讨  
在[Oracle](http://lib.csdn.net/base/oracle "Oracle知识库")的update语句语法中，除了可以update表之外，也可以是视图，所以有以下1个特例：

SQL 代码

1. update (select a.city\_name,b.city\_name as new\_name
2. from customers a,
3. tmp\_cust\_city b
4. where b.customer\_id=a.customer\_id
5. )
6. set city\_name=new\_name

这样能避免对B表或其索引的2次扫描，但前提是 A(customer\_id) b(customer\_id)必需是unique index或primary key