前言
一个一个例子来,获取最大值max的优化。求数据的最大值,说实在话在我们的实际开发中还是挺好用的。可能数据表一万两万的时候不是很看的出来性能,但是任何东西都顶不住数量多啊。为了模拟这个数量多的环境,不废话,贴出代码,方便大家。
创建所需要的数据表以及数据
先来 300W
数据压压惊,我们来找 age
来找大哥,看谁才是最牛逼,最大的人。
1 | -- 创建数据表 |
2 | DROP TABLE IF EXISTS `testemployee`; |
3 | CREATE TABLE `testemployee` ( |
4 | `id` int(11) NOT NULL AUTO_INCREMENT, |
5 | `name` VARCHAR(20) DEFAULT NULL, |
6 | `dep_id` int(11) DEFAULT NULL, |
7 | `age` int(11) DEFAULT NULL, |
8 | `salary` DECIMAL(10, 2) DEFAULT NULL, |
9 | `cus_id` int(11) DEFAULT NULL, |
10 | PRIMARY key(`id`) |
11 | ) ENGINE = INNODB DEFAULT CHARSET=utf8mb4; |
12 | |
13 | -- 随机生成字符串 |
14 | delimiter $$ |
15 | DROP FUNCTION IF EXISTS `rand_str`; |
16 | CREATE FUNCTION rand_str(n int) RETURNS varchar(255) |
17 | BEGIN |
18 | declare str varchar(100) default 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'; |
19 | declare i int default 0; |
20 | declare res_str varchar(255) default 'php_'; |
21 | |
22 | while i < n do |
23 | SET res_str = CONCAT(res_str, SUBSTR(str, FLOOR(1 + RAND()*52), 1)); |
24 | SET i = i + 1; |
25 | end while; |
26 | |
27 | return res_str; |
28 | END$$ |
29 | delimiter ; |
30 | |
31 | -- 存储过程 |
32 | CREATE DEFINER=`root`@`localhost` PROCEDURE `insert_emp`(in max_num int) |
33 | BEGIN |
34 | DECLARE i INT DEFAULT 0; |
35 | SET autocommit = 0; |
36 | repeat |
37 | set i = i + 1; |
38 | insert into `testemployee` (name, dep_id, age, salary, cus_id) VALUES (rand_str(5), floor(1+rand()*10), floor(20 + RAND()*10), floor(2000 + RAND()*10), FLOOR(1 + RAND()*10)); |
39 | UNTIL i = max_num |
40 | end repeat; |
41 | |
42 | commit; |
43 | END |
44 | |
45 | -- 记得CALL,300W个数据先玩玩 |
46 | CALL insert_emp(3000000) |
常规max操作看看性能
1 | -- Time: 5.501s |
2 | SELECT max(age) FROM testemployee; |
怀疑人生的时常吖,五秒多出现在服务器上简直就是一场灾难。这里我们发现 age
并没有索引对吧,那就干索引吧。
1 | -- 索引搞起来 |
2 | CREATE INDEX idx_age ON testemployee(age); |
3 | |
4 | -- Time: 0.024s |
5 | SELECT max(age) FROM testemployee; |
总结
其实这个优化不是很难,主要的还是要自己去动手把东西都做一遍,代码都给出来,欢迎大家自己动手去写写。