前言:
MySQL版本5.7.30
建表:
CREATE TABLE `product` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`),
KEY `name` (`name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/**
* 创建副表
*/
CREATE TABLE `product2` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`name` varchar(20) DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
造数据:
delimiter $$
create procedure p1(in num int)
begin
declare name varchar(20) default '';
declare i int default 1;
while i<= num do
set name = concat('panda',i);
insert into product (`name`) values(name);
set i = i+1;
end while;
end $$
delimiter ;
call p1(1000000);
先建索引后迁移数据:
/**
* 500w条(2m7s)
* 先建索引,后迁移数据
*/
ALTER TABLE product2 ADD INDEX index_my_name (`name`);# 290ms
INSERT INTO product2 SELECT * FROM product;# 2m6s
先迁移数据后建索引:
/**
* 500w条(2m4s)
* 先迁移数据,后建索引
*/
INSERT INTO product2 SELECT * FROM product;# 1m22s
ALTER TABLE product2 ADD INDEX index_my_name (`name`); # 42s
结论:
两种方式的整体耗时相差不大,但是后创建索引迁移数据时耗时较少