oracle多表关联更新(update)/删除(delete)数据表的的写法

 1) 两表(多表)关联update -- 仅在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. )

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

SQL 代码
  1. update customers a -- 使用别名
  2. set city_name=(select b.city_name from tmp_cust_city b where b.customer_id=a.customer_id)
  3. where exists (select 1
  4. from tmp_cust_city b
  5. where b.customer_id=a.customer_id
  6. )
  7. -- update 超过2个值
  8. update customers a -- 使用别名
  9. set (city_name,customer_type)=(select b.city_name,b.customer_type
  10. from tmp_cust_city b
  11. where b.customer_id=a.customer_id)
  12. where exists (select 1
  13. from tmp_cust_city b
  14. where b.customer_id=a.customer_id
  15. )

注意在这个语句中,
=(
select b.city_name,b.customer_type from tmp_cust_city b
where b.customer_id=a.customer_id )

(
select from tmp_cust_city b
where b.customer_id=a.customer_id)
是两个独立的子查询,查看执行计划可知,对b表/索引扫描了
2篇;

3) 在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. )

二、oracle多表关联删除的两种方法

第一种使用exists方法

  1. delete  
  2. from tableA  
  3. where exits  
  4. (  
  5.      select 1  
  6.      from tableB  
  7.      Where tableA.id = tableB.id  
  8. )  
第二种使用匿名表方式进行删除
  1. delete  
  2. from  
  3. (  
  4.       select 1  
  5.       from tableA,TableB  
  6.       where tableA.id = tableB.id  
  7. )

你可能感兴趣的:(Oracle,开发,Oracle)