今天从慢查询发现一条语句查询时间达6秒。结果只查出一条记录。
原语句如下
SELECT biz_order_id, buyer_id, buyer_nick, gmt_create, gmt_modified, attributeCc, seller_id
FROM trade.biz_order
WHERE shop_id=20484 AND STATUS=4 AND gmt_create
>= '2017-10-30 16:34:42' AND order_type = 6
ORDER BY gmt_create DESC, biz_order_id DESC
LIMIT 0,100;
执行计划
shop_id都有索引可却走了时间gmt_create的索引,rows=861665
优化方法3种:
1:强制走shop_id索引
SELECT biz_order_id, buyer_id, buyer_nick, gmt_create, gmt_modified, attributeCc, seller_id
FROM trade.biz_order force index(idx_shop_id)
WHERE shop_id=20484 AND STATUS=4 AND gmt_create
>= '2017-10-30 16:34:42' AND order_type = 6
ORDER BY gmt_create DESC, biz_order_id DESC
LIMIT 0,100;
2:用子查询:
select * from ( SELECT biz_order_id, buyer_id, buyer_nick, gmt_create, gmt_modified, attributeCc, seller_id
FROM trade.biz_order
WHERE shop_id=20484 AND STATUS=4 AND gmt_create >= '2017-10-30 16:34:42' AND order_type = 6
ORDER BY gmt_create DESC, biz_order_id DESC) t
LIMIT 0,100;执行计划如上一样
3:调换order by中的两个条件顺序
ORDER BY biz_order_id DESC ,gmt_create DESC limit 0,100;换成这样。我发现这样执行计划的rows=1.9万效果更好。
4:还有一种方法删除gmt_create列的索引,原理和方法3差不多。
总结:mysql中的order ,limit一起使用时的顺序是这样的和oracle不一样
order -->limit-->where条件
而常规一般是where-->order-->limit。