MySQL 触发器功能比较简单,大部分只用来简单的更新第三方表,今天我来演示下MySQL触发器在造数据方面的功效。
下面是基表结果:
CREATE TABLE `tb1` (
`id` varchar(255) NOT NULL,
`log_date` date DEFAULT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8 ROW_FORMAT=FIXED
这个是对基表的批量插入存储过程:
CREATE DEFINER = 'root'@'localhost'
PROCEDURE db_myisam.sp_generate_tb1_data(IN cur_1 INT,
IN f_input INT,
IN f_commit_num INT
-- Stands for which month's date.
)
BEGIN
DECLARE t_count INT;
DECLARE v_log_date DATE;
DECLARE c_date DATE DEFAULT '2012-07-01';
SET t_count = cur_1 + (f_input - 1);
SET @@autocommit = 0;
WHILE cur_1 <= t_count
DO
IF mod(cur_1, f_commit_num) = 1 THEN
START TRANSACTION;
END IF;
SET v_log_date = date_add(c_date, INTERVAL ceil(rand() * 3) * (ceil(rand() * 15)) DAY);
INSERT INTO tb1 (id, log_date) VALUES (cur_1, v_log_date);
IF mod(cur_1, f_commit_num) = 0 THEN
COMMIT;
END IF;
SET cur_1 = cur_1 + 1;
END WHILE;
COMMIT;
END
CREATE
DEFINER = 'root'@'localhost'
TRIGGER db_myisam.ti_tb3_after
AFTER INSERT
ON db_myisam.tb3
FOR EACH ROW
BEGIN
DECLARE v_cur_1 INT DEFAULT 1;
DECLARE v_log_date DATE;
DECLARE c_date DATE DEFAULT '2012-07-01';
WHILE v_cur_1 <= 10000000
DO
SET v_log_date = date_add(c_date, INTERVAL ceil(rand() * 3) * (ceil(rand() * 15)) DAY);
INSERT INTO tb2 (id, log_date) VALUES (v_cur_1, v_log_date);
SET v_cur_1 = v_cur_1 + 1;
END WHILE;
END
1KW记录花了不到6分钟,也就是一个线程每秒插入大于3W记录。
mysql> insert into tb3 values (2,current_date());
Query OK, 1 row affected (5 min 14.07 sec)