在实战项目中,函数使用不当导致索引失效,导出数据过慢

在实战项目中,函数使用不当导致索引失效,导出数据过慢

讲一讲最近碰到的小问题

一个用于统计的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
  • 效果还是有的,当数据量大时候更加明显
  • 2
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

IT枫斗者

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值