1.在測試一個按照時間的範圍查詢時,儘管增加了索引,發現使用不到索引,可以使用這個來強制使用索引 測試過程為,創建下麵的表,以及創建了聯合索引 create table delay_delete_users( id int auto_increment, email_id int not null ...
1.在測試一個按照時間的範圍查詢時,儘管增加了索引,發現使用不到索引,可以使用這個來強制使用索引
測試過程為,創建下麵的表,以及創建了聯合索引
create table delay_delete_users( id int auto_increment, email_id int not null default 0 comment 'email表id', email varchar(50) not null default '' comment '郵箱首碼', entid int not null default 0 comment '企業id', default_domain varchar(50) not null default '' comment '預設域', delete_time timestamp comment '刪除時間', clear tinyint not null default 0 comment '0未處理,1已清空', primary key (id), key email_entid(email,entid), key delete_time(delete_time,clear) )engine innodb;
插入測試數據,進行explain查詢
insert into `delay_delete_users` (email,entid,default_domain,delete_time)value('shihan2',23684,'appdev.sinanet.com','2019-12-10 15:49:16'); insert into `delay_delete_users` (email,entid,default_domain,delete_time,clear)value('shihan2',23684,'appdev.sinanet.com','2019-12-10 15:49:16',1); insert into `delay_delete_users` (email,entid,default_domain,delete_time,clear)value('shihan2',23684,'appdev.sinanet.com','2019-12-12 15:49:16',1);
explain select * from delay_delete_users where delete_time<'2019-12-12' and clear=0; 索引沒有使用到,還是進行的全表掃描,看那個掃描行數rows
+----+-------------+--------------------+------------+------+---------------+------+---------+------+------+----------+-------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+--------------------+------------+------+---------------+------+---------+------+------+----------+-------------+ | 1 | SIMPLE | delay_delete_users | NULL | ALL | delete_time | NULL | NULL | NULL | 7 | 14.29 | Using where |
explain select * from delay_delete_users force index(delete_time) where delete_time<'2019-12-12' and clear=0;使用到了索引
+----+-------------+--------------------+------------+-------+---------------+-------------+---------+------+------+----------+-----------------------+ | id | select_type | table | partitions | type | possible_keys | key | key_len | ref | rows | filtered | Extra | +----+-------------+--------------------+------------+-------+---------------+-------------+---------+------+------+----------+-----------------------+ | 1 | SIMPLE | delay_delete_users | NULL | range | delete_time | delete_time | 4 | NULL | 3 | 14.29 | Using index condition |