业务场景:查找某个人的历史记录,如果前端传来userid,我们直接在userid建立索引的话,那么按照时间排序就会有排序的情况,即extra会有filesort标志,我们可以利用联合索引建立(userid,time)的联合索引,保证他们两个就是有序的。注意,这里如果数据量过小,mysql的优化器就会将他们全表扫描
INSERT INTO history_record VALUES ('1','1','baidu','tencent',NOW(),12,13);
INSERT INTO history_record VALUES ('2','1','baidu','tencent',NOW(),12,13);
INSERT INTO history_record VALUES ('3','1','baidu','tencent',NOW(),12,13);
INSERT INTO history_record VALUES ('4','1','baidu','tencent',NOW(),12,13);
INSERT INTO history_record VALUES ('5','1','baidu','tencent',NOW(),12,13);
INSERT INTO history_record VALUES ('6','1','baidu','tencent',NOW(),12,13);
INSERT INTO history_record VALUES ('7','1','baidu','tencent',NOW(),12,13);
SELECT * FROM history_record
EXPLAIN SELECT user_id, TIME FROM history_record WHERE user_id = 1 ORDER BY TIME
CREATE TABLE `history_record` (
`id` INT(32) PRIMARY KEY AUTO_INCREMENT,
`user_id` INT(32) NOT NULL,
`url` VARCHAR(255) NOT NULL,
`cover` VARCHAR(255) NOT NULL,
`time` DATETIME NOT NULL,
`width` INT(6) NOT NULL,
`height` INT(6) NOT NULL,
KEY `user_id_time` (`user_id`,`time`)
) ENGINE=INNODB DEFAULT CHARSET=utf8mb4
SELECT COUNT(*) FROM history_record
EXPLAIN SELECT * FROM history_record WHERE user_id = 1 ORDER BY TIME
TRUNCATE TABLE history_record; #清空表数据
DROP PROCEDURE IF EXISTS proc_init_data; #如果存在此存储过程则删掉
DELIMITER $ -- 使用delimiter后,将不把分号当做语句结束,会将该段整个提交
CREATE PROCEDURE proc_init_data()
BEGIN
DECLARE j INT DEFAULT 1;
DECLARE i INT DEFAULT 1;
WHILE j<=200 DO
SET i = 1;
WHILE i<=50 DO
INSERT INTO history_record(user_id, url, cover, TIME, width,height) VALUES (i,'baidu','tencent',NOW(),12,13);
SET i = i+1;
END WHILE;
SET j = j + 1;
END WHILE;
END $
CALL proc_init_data();