分表数据迁移方案

2016/08/28 1041点热度 0人点赞 0条评论

有一个需求,一张表中有1亿条数据,现在要分表处理。数据分离是个麻烦事。以下为本人的解决方案。效率还行。

-- 创建测试表
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;
-- 测试数据
INSERT INTO `test`.`user` (`id`, `name`) VALUES ('1', '1');
INSERT INTO `test`.`user` (`id`, `name`) VALUES ('2', '2');
INSERT INTO `test`.`user` (`id`, `name`) VALUES ('3', '3');
INSERT INTO `test`.`user` (`id`, `name`) VALUES ('4', '4');
INSERT INTO `test`.`user` (`id`, `name`) VALUES ('5', '5');
-- 分表1
CREATE TABLE `user_1` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(255) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

-- 创建存储过程
CREATE  PROCEDURE `insertInit`()
BEGIN
	declare total int(11); -- 总循环次数
	declare idx int(11); -- 当前循环
	declare maxId int(11); -- 每次循环查询条件的最大id
	declare limitNum int(11); -- 分页查询的数据
	set total = 2;
	set idx = 0;
  set maxId= 1;
	set limitNum=1;
  while idx <= total do
     insert into user_1 SELECT * from `user` u where u.id>maxId -- 分表条件
 	 LIMIT limitNum; -- 每次从最大id取对应的n条数据
     SELECT  max(id) into maxId from user_1; -- 获取当前导入后的maxId
     set idx = idx+1;
  end while;

END

yxkong

这个人很懒,什么都没留下

文章评论