drop TABLE if EXISTS test_order;
create table test_order
(
id int auto_increment primary key,
user_id int,
order_id int,
order_status tinyint,
create_date datetime
);
create index idx_userid_order_id_createdate on test_order(user_id,order_id,create_date);
show index from test_order;
drop PROCEDURE IF EXISTS test_insertdata;
delimiter //
CREATE PROCEDURE `test_insertdata`(IN `loopcount` INT)
BEGIN
declare v_uuid varchar(50);
while loopcount>0 do
set v_uuid = uuid();
insert into test_order (user_id,order_id,order_status,create_date) values (rand()*1000,rand()*1000,rand()*10,DATE_ADD(NOW(), INTERVAL - RAND()*20000 HOUR));
set loopcount = loopcount -1;
end while;
END;
//
delimiter ;
SET @loopcount = 1000000;
CALL test_insertdata(@loopcount)
环境:100w条数据
不添加索引 VS 添加索引
不添加索引:
搜索时间为0.348秒
添加索引:
搜索时间大概为0.048秒
聚集索引 VS 辅助索引
聚集索引:
辅助索引:
、
create index idx_userid_order_id_createdate on test_order(user_id,order_id,create_date);
因为联合索引中没有order_status这个字段,所以辅助索引查询到主键后再查询聚集索引,找到order_status这个字段的值。分成两部。所以消耗的时间比聚集索引时间要长。
覆盖索引 VS 辅助索引
--Using index
--查询的列被索引覆盖,并且where筛选条件是索引的是前导列,Extra中为Using index
explain select user_id, order_id,create_date from test_order where user_id = 1;
explain select * from test_order where user_id = 1;