Oracle 的 update 语句优化研究
一、 update 语句的语法与原理
1. 语法
单表:UPDATE 表名称 SET 列名称 = 新值 WHERE 列名称 = 某值
如:update t_join_situation set join_state='1' where
year='2011'
更新年度为“2011”的数据的 join_state 字段为“1”。如果更新的字段加了
索引,更新时会重建索引,更新效率会慢。
多表关联,并把一个表的字段值更新到另一个表中的字段去:
update 表 a set a.字段 1 = (select b.字段 1 from 表 b where
a.字段 2=b.字段 2) where exists(select 1 from 表 b where a.
字段 2=b.字段 2)
oracle 的更新语句不通 MSSQL 那么简单易写,就算写出来了,但执行时可
能会报
这是由于 set 哪里的子查询查出了多行数据值,oracle 规定一对一更新数据,
所以提示出错。要解决这样必须保证查出来的值一一对应。
2. 原理
Update 语句的原理是先根据 where 条件查到数据后,如果 set 中有子查询,则
执行子查询把值查出来赋给更新的字段,执行更新。
如:update 表 a set a.字段 1 = (select b.字段 1 from 表 b
where a.字段 2=b.字段 2) where exists(select 1 from 表 b
where a.字段 2=b.字段 2)。查表 a 的所有数据,循环每条数据,验证该条
数据是否符合 exists(select 1 from 表 b where a.字段 2=b.字段 2)
条件,如果是则执行(select b.字段 1 from 表 b where a.字段 2=b.
字段 2)查询,查到对应的值更新 a.字段 1 中。关联表更新时一定要有
exists(select 1 from 表 b where a.字段 2=b.字段 2)这样的条件,
否则将表 a 的其他数据的字段 1 更新为 null 值。
二、 提高 oracle 更新效率的各种解决方案
评论0