索引失效场景
我们平常在开发的过程中都会做一些历史数据通过时间去筛选数据的接口,当时是对一张历史数据表做查询,历史数据表的数据量大概有500W条,平均一秒写三条数据到这张表,有一天突然发现页面查询变的非常缓慢,于是对这个接口进行排查,首先执行这个历史数据的查询SQL,SQL如下:
select count(id) as flowNum,DATE_FORMAT(create_date,'%Y-%m') as monthDate,image_source as pictureSource
from flow_picture_info where delete_flag=false and image_status=true
and date_format(create_date,'%Y-%m-%d') >= '2020-01-01'
and date_format(create_date,'%Y-%m-%d') <= '2020-08-08'
group by monthDate,image_source
执行这段SQL以后发现执行时间为27.93s,这怎么能忍,执行查询计划看一下:
发现没走索引
解决方案
将date_format函数进行改写,改写SQL如下:
explain select count(id) as flowNum,DATE_FORMAT(create_date,'%Y-%m') as monthDate,image_source as pictureSource
from flow_picture_info where delete_flag=false and image_status=true
and create_date >= STR_TO_DATE('2020-01-01','%Y-%m-%d')
and create_date <= STR_TO_DATE('2020-08-08','%Y-%m-%d')
group by monthDate,image_source
执行查询计划:
还有其它方式,可以使用between…and方法进行日期筛选