mysql sql force_index 优化案例

下面的sql运行了27秒
explain SELECT
-> COUNT(1)
-> FROM
-> (SELECT
-> t3.store_id
-> FROM
-> dmall_tmp.wm_order t1 , dmall_oop.store t2, dmall_dw.dm_store t3
-> WHERE
-> t1.shop_id = t2.sap_id
-> AND t2.id = t3.ori_store_id
-> AND t1.order_create_time >= 20160504
-> AND t1.order_create_time <= 20160505
-> AND t3.store_id IN (718 , 719, 720, 4262, 4263, 4264, 4265, 4266, 4267, 4268, 4269, 4270, 4271, 4272, 4439, 4440, 4637, 4638, 4639, 5709, 5710, 5712, 5713)
-> GROUP BY DATE_FORMAT(t1.order_create_time, ‘%Y%m%d’) , t3.store_id) a;
+——+————-+————+——–+—————————+———+———+————————–+——+———————————————-+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+——+————-+————+——–+—————————+———+———+————————–+——+———————————————-+
| 1 | PRIMARY | | ALL | NULL | NULL | NULL | NULL | 5451 | |
| 2 | DERIVED | t3 | range | PRIMARY,iindex | PRIMARY | 4 | NULL | 23 | Using where; Using temporary; Using filesort |
| 2 | DERIVED | t2 | eq_ref | PRIMARY,sap_id | PRIMARY | 4 | dmall_dw.t3.ori_store_id | 1 | Using where |
| 2 | DERIVED | t1 | ref | shop_id,order_create_time | shop_id | 8 | dmall_oop.t2.sap_id | 237 | Using index condition; Using where |
+——+————-+————+——–+—————————+———+———+————————–+——+———————————————-+
4 rows in set (0.00 sec)
我们看到在最下面的一行中,使用了shop_id去连接了,没有使用到order_create_time,而时间列的过滤性是十分强的,最好的情况就是按时间过滤后,再去关联,这样结果集就小很多,按照这个思路,我们让t1使用时间列上的索引

explain SELECT
-> count(*)
-> FROM
-> dmall_tmp.wm_order t1 FORCE INDEX(order_create_time), dmall_oop.store t2, dmall_dw.dm_store t3
-> WHERE
-> t1.shop_id = t2.sap_id
-> AND t2.id = t3.ori_store_id
-> AND t1.order_create_time >= 20160504
-> AND t1.order_create_time <= 20160505
-> AND t3.store_id IN (718 , 719, 720, 4262, 4263, 4264, 4265, 4266, 4267, 4268, 4269, 4270, 4271, 4272, 4439, 4440, 4637, 4638, 4639, 5709, 5710, 5712, 5713);
+——+————-+——-+——–+——————-+——————-+———+————————–+——-+————————————+
| id | select_type | table | type | possible_keys | key | key_len | ref | rows | Extra |
+——+————-+——-+——–+——————-+——————-+———+————————–+——-+————————————+
| 1 | SIMPLE | t3 | range | PRIMARY,iindex | PRIMARY | 4 | NULL | 23 | Using where |
| 1 | SIMPLE | t2 | eq_ref | PRIMARY,sap_id | PRIMARY | 4 | dmall_dw.t3.ori_store_id | 1 | Using where |
| 1 | SIMPLE | t1 | range | order_create_time | order_create_time | 9 | NULL | 87108 | Using index condition; Using where |
+——+————-+——-+——–+——————-+——————-+———+————————–+——-+————————————+
虽然t1的结果集变大了,但是没有了,实际执行时间下将到2s

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值