最近在优化慢sql,发现很多表加了索引也没用,还是全表扫描。
表结构:
CREATE TABLE `t_order_push_log` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`order_no` varchar(50) NOT NULL COMMENT '',
`target` varchar(20) NOT NULL COMMENT '',
`content` text NOT NULL COMMENT '',
`push_time` datetime NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '',
`push_status` tinyint(2) NOT NULL DEFAULT '-1' COMMENT '',
`msg` varchar(10000) DEFAULT NULL COMMENT '',
`gmt_create` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '',
`gmt_modify` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '',
`remark` varchar(255) DEFAULT NULL COMMENT '',
`version` int(11) DEFAULT '0' COMMENT ',
PRIMARY KEY (`id`) USING BTREE,
) ENGINE=InnoDB AUTO_INCREMENT=59 DEFAULT CHARSET=utf8mb4 COMMENT='';
执行语句:
select id, order_no, target, content, push_time
, push_status, msg, gmt_create, gmt_modify, version
from t_order_push_log
where push_status = 1
and gmt_create >= '1'
看执行计划:
全表扫描
添加索引:
alter table t_order_push_log add index idx_push_status (push_status);
alter table t_order_push_log add index idx_gmt_create (gmt_create);
添加索引后发现还是全表扫描
此时发现sql语句字段值不对
将条件 gmt_create >= '2021-11-11' 修改 发现还是没有走索引
这个时候需要添加联合索引,因为条件用的是二个字段,单独设立索引是不生效的
alter table t_order_push_log add index idx_status_gmt (push_status,gmt_create);
最后执行结果