[MySQL] 使用force index强制使用索引
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 |
十年开发经验程序员,离职全心创业中,历时三年开发出的产品《唯一客服系统》
一款基于Golang+Vue开发的在线客服系统,软件著作权编号:2021SR1462600。一套可私有化部署的网站在线客服系统,编译后的二进制文件可直接使用无需搭开发环境,下载zip解压即可,仅依赖MySQL数据库,是一个开箱即用的全渠道在线客服系统,致力于帮助广大开发者/公司快速部署整合私有化客服功能。
开源地址:唯一客服(开源学习版)
官网地址:唯一客服官网