从备份表中更新字段到正式表中,使用 update 批量更新大量的数据,会出现效率低下,有时候甚至卡死的情况,后面通过使用 merge into 代替 update 执行批量更新,会提升执行效率。
merge into语法如下:
merge into table_name alias1
using (table|view|sub_query) alias2
on (join condition)
when matched then
update
set col1 = col1_val1,
col2 = col2_val2
when not matched then
insert (column_list) values (column_values); 其中,table_name 指的是更新的表,using()里边的指的是数据来源表/视图/子查询结果集,condition指的是连接条件,如果满足连接条件,set 字段1=值1,字段2=值2...
如果连接条件不满足,则停止更新进行插入。
下面我们来举例说明:
先创建被更新表merge_target,并往其中插入一条数据用来更新;

再创建更新表merge_source,用来向被更新表插入数据;

下面准备merge into脚本:
merge into merge_target target
using (select b.name,b.age,b.target_id from merge_source b) source
on (target.id=source.target_id)
when matched then
update
set target.name = source.name,
target.age = source.age
when not matched then
insert(target.name,target.age) values (source.name,source.age); 结果如下:

另:mysql不支持merge into 语法。
发表评论