一 前言
1.查了很多资料,replace into也好 insert into on duplicate key update 也好,都需要原始数据表具有唯一性索引。
2.网上方法很多,最简便还是使用如上语句,如果不想创建唯一性索引,则可以通过存储过程实现。不解释连招如下。
二 实验
-- 创建测试表 -- drop table test_a; create table test_a( id varchar (16), name varchar (16), operatime datetime ) -- drop table test_b; create table test_b( id varchar (16), name varchar (16), operatime datetime ) -- 插入模拟数据 insert into test_b values(1,"1",now()),(2,"2",now()); insert into test_a values(1,"1",now()),(3,"3",now()); -- 查询数据 select * from test_b; select * from test_a;
delimiter $ create procedure merge_a_to_b () begin -- 定义需要插入从a表插入b表的过程变量 declare _id varchar (16); declare _name varchar (16); -- 游标遍历数据结束标志 declare done int default false; -- 游标指向a表结果集第一条-1位置 declare cur_account cursor for select id, name from test_a; -- 游标指向a表结果集最后一条加1位置 设置结束标志 declare continue handler for not found set done = true; -- 打开游标 open cur_account; -- 遍历游标 read_loop : loop -- 取值a表当前位置数据到临时变量 fetch next from cur_account into _id,_name; -- 如果取值结束 跳出循环 if done then leave read_loop; end if; -- 当前数据做 对比 如果b表存在则更新时间 不存在则插入 if not exists ( select 1 from test_b where id = _id and name=_name ) then insert into test_b (id, name,operatime) values (_id,_name,now()); else update test_b set operatime = now() where id = _id and name=_name; end if; end loop; close cur_account; end $
三 验证
-- 验证语句 select * from test_b; select * from test_a; call merge_a_to_b(); select * from test_b; select * from test_a;
- 操作前
- 操作后
数据1更新 数据3插入 ok
总结
以上为个人经验,希望能给大家一个参考,也希望大家多多支持代码网。
发表评论