在实战项目中,函数使用不当导致索引失效,导出数据过慢
讲一讲最近碰到的小问题
一个用于统计的sql压测发现比较慢
- 原因是sql中需要统计当天的数据,因为函数使用不当导致索引失效
原sql
-
select ifnull(( select count(1) from d_application a where a.stste = 53 and a.auditopentity = 'a'), 0) auditQuantity, count(distinct d.appoid) rea from d_app d, d_application t where d.appoid = t.id and t.auditopentity = 'a' and to_days(d.createdate) = to_days(now())
-
通过sql的执行计划我们可以看出d_app这张表并没有走索引,时进行的全表扫描,虽然createdate这个字段添加了索引,但是这个字段在函数to_days中,导致并没有按照索引进行查询,造成速度很慢
修改后sql
-
select ifnull(( select count(1) from d_application a where a.stste = 53 and a.auditopentity = 'a'), 0) auditQuantity, count(distinct d.appoid) rea from d_app d, d_application t where d.appoid = t.id and t.auditopentity = 'a' and d.createdate > date_format(now(), '%Y-%m-%d')
-
我们将查询当天的函数表达式修改成d.createdate > date_format(now(), ‘%Y-%m-%d’),执行时不是全表扫描
优化后
- 修改前是2245ms,修改后是144ms
- 效果还是有的,当数据量大时候更加明显