先模拟数据:
DROP DATABASE IF EXISTS TEST;
create database TEST charset utf8;
use oldboy;
CREATE TABLE t_100w (id INT,num INT,k1 CHAR(2),k2 CHAR(4),dt TIMESTAMP);
DELIMITER //
CREATE PROCEDURE rand_data(IN num INT)
BEGIN
DECLARE str CHAR(62) DEFAULT 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789';
DECLARE str2 CHAR(2);
DECLARE str4 CHAR(4);
DECLARE i INT DEFAULT 0;
WHILE i<num DO
SET str2=CONCAT(SUBSTRING(str,1+FLOOR(RAND()*61),1),SUBSTRING(str,1+FLOOR(RAND()*61),1));
SET str4=CONCAT(SUBSTRING(str,1+FLOOR(RAND()*61),2),SUBSTRING(str,1+FLOOR(RAND()*61),2));
SET i=i+1;
INSERT INTO t_100w VALUES (i,FLOOR(RAND()*num),str2,str4,NOW());
END WHILE;
END;
//
DELIMITER ;
CALL rand_data(1000000);
COMMIT;
#查询数据是否正确
select count(*) from TEST.t_100w;
----------+
| count(*) |
+----------+
| 1000000 |
+----------+
如上数据已经准备好;
下一步在linux下下执行如下压力测试语句:
home/mysql8.0.16/mysql/bin/mysqlslap --defaults-file=/home/mysql8.0.16/mysql/my.cnf --concurrency=100 --iterations=1 --create-schema='test' --query="select * from test.t_100w where k2='CD23'" ENGINE=INNODB --number-of-queries=2000 -uroot -p'123456' -P3307 -verbose
可以看到当前没有创建任何索引的情况下查询2000次的时间为109.204秒;
原因没有创建索引:
DESC SELECT * FROM t_100w WHERE k2='CD23' ;
SHOW INDEX FROM t_100w;
ALTER TABLE t_100w ADD INDEX idx(k2);
DESC SELECT * FROM t_100w WHERE k2='CD23'
现在将查询语句进行优化,添加索引后重新执行命令后结果如下:
我们发现时间由109多秒缩减到只有3.7s左右,