USING (table|view|sub_query) alias2
ON (join condition)
WHEN MATCHED THEN
UPDATE table_name
SET col1 = col_val1,
col2 = col2_val
WHEN NOT MATCHED THEN
INSERT (column_list) VALUES (column_values); 它的原理是在alias2中Select出来的数据,每一条都跟alias1进行 ON (join condition)的比较,如果匹配,就进行更新的操作(Update),如果不匹配,就进行插入操作(Insert)。执行merge不会返回影响的行数。Merge语句的写法比较繁琐,并且最多只能两个表关联,复杂的语句用merge更新法将力不从心且效率差。 4.快速游标更新法 语法如: begin for cr in (查询语句) loop –-循环 --更新语句(根据查询出来的结果集合) endloop; --结束循环 end; oracle支持快速游标,不需要定义直接把游标写到for循环中,这样就方便了我们批量更新数据。再加上oracle的rowid物理字段(oracle默认给每个表都有rowid这个字段,并且是唯一索引),可以快速定位到要更新的记录上。 例子如下: begin for cr in (select a.rowid,b.join_state from t_join_situation a,t_people_info b where a.people_number=b.people_number and a.year=‘2011‘and a.city_number=‘M00000‘and a.town_number=‘M51000‘) loop update t_join_situation set join_state=cr.join_state where rowid = cr.rowid; endloop; end; 使用快速游标的好处很多,可以支持复杂的查询语句,更新准确,无论数据多大更新效率仍然高,但执行后不返回影响行数。 三、结论
| 方案 | 建议 |
| 标准update语法 | 单表更新或较简单的语句采用使用此方案更优。 |
| inline view更新法 | 两表关联且被更新表通过关联表主键关联的,采用此方案更优。 |
| merge更新法 | 两表关联且被更新表不是通过关联表主键关联的,采用此方案更优。 |
| 快速游标更新法 | 多表关联且逻辑复杂的,采用此方案更优。 |
实时测试的速度: --48466条数据 --1.297 update (select a.join_state as join_state_a,b.join_state as join_state_b from t_join_situation a, t_people_info b where a.people_number=b.people_number and a.year=‘2011‘and a.city_number=‘M00000‘and a.town_number=‘M51000‘ ) set join_state_a=join_state_b --7.156 update t_join_situation a set a.join_state=(select b.join_state from t_people_info b where a.people_number=b.people_number and a.year=‘2011‘and a.city_number=‘M00000‘and a.town_number=‘M51000‘) whereexists (select1from t_people_info b where a.people_number=b.people_number and a.year=‘2011‘and a.city_number=‘M00000‘and a.town_number=‘M51000‘) --3.281 begin for cr in (select a.rowid,b.join_state from t_join_situation a,t_people_info b where a.people_number=b.people_number and a.year=‘2011‘and a.city_number=‘M00000‘and a.town_number=‘M51000‘) loop update t_join_situation set join_state=cr.join_state where rowid = cr.rowid; endloop; end; --1.641 mergeinto t_join_situation a using t_people_info b on (a.people_number=b.people_number and a.year=‘2011‘and a.city_number=‘M00000‘and a.town_number=‘M51000‘) whenmatchedthenupdateset a.join_state=b.join_state
Oracle的update语句优化研究
标签: