前言

为了体现不加索引和增加索引的区别,须要应用百万级的数据,然而百万数据的表,如果应用一条条增加,特地繁琐又麻烦,这里应用存储过程疾速增加数据,用时大略4个小时。
创立一个用户表

CREATE TABLE `t_sales` (  `id` int(11) NOT NULL AUTO_INCREMENT,  `username` varchar(32) COLLATE utf8_bin DEFAULT NULL COMMENT '用户名',  `password` varchar(64) COLLATE utf8_bin DEFAULT NULL COMMENT '明码 MD5存储',  `register_time` timestamp NULL DEFAULT NULL COMMENT '注册工夫',  `type` int(1) DEFAULT NULL COMMENT '用户类型 1,2,3,4 随机',  PRIMARY KEY (`id`),  KEY `idx_username` (`username`) USING BTREE)

而后创立存储过程,批量增加数据。

  • 用户名以常量和数字拼接
  • 明码是MD5明码
  • 注册工夫是以后工夫随机往前推几天
  • type是取1-4随机范畴值

    create procedure salesAdd()begin  declare i int default 11; while i <= 4000000 do       insert into blog.t_sales       (`username`,`password`,`register_time`,type) values       (concat("jack",i),MD5(concat("psswe",i)),from_unixtime(unix_timestamp(now()) - floor(rand() * 800000)),floor(1 + rand() * 4));        set i = i + 1;  end while; end

    而后调用存储过程

    call salesAdd()

改进版

尽管应用存储过程增加数据绝对一个个增加更加便捷,疾速,然而增加几百万数据要花几个小时工夫也是很久的,前面在网上找到不少材料,发现mysql每次执行一条语句都默认主动提交,这个操作十分耗时,所以在在增加去掉主动提交。设置 SET AUTOCOMMIT = 0;

create procedure salesAdd()begin  declare i int default 1; set autocommit = 0;      while i <= 4000000 do         insert into blog.t_sales         (`username`,`password`,`register_time`,type) values         (concat("jack",i),MD5(concat("psswe",i)),from_unixtime(unix_timestamp(now()) - floor(rand() * 800000)),floor(1 + rand() * 4));          set i = i + 1;    end while; set autocommit = 1;     end

执行工夫387秒,约为六分钟,其中还有一半工夫用于md5、随机数的计算。

[SQL]call salesAdd();受影响的行: 0工夫: 387.691s