如何优化 MySQL 商品销售情况统计查询性能,使其在查询时间范围扩大时也能保持快速响应?

如何优化 mysql 商品销售情况统计查询性能,使其在查询时间范围扩大时也能保持快速响应?

优化 mysql 商品销售情况统计查询性能

问题描述:

针对如下 sql 查询:

select p.title,
       count(o.id)                    as total,
       coalesce(sum(o.amount), 0)     as success_amount,
coalesce(sum(success.amount), 0)     as failed_amount,
coalesce(sum(failed.amount), 0)     as total_amount,
count(success.id) as success_total,
count(failed.id) as failed_total
from goods as g
         left join orders as o on o.goods_id = g.id
         left join orders as success on success.goods_id = g.id and success.status = 1 
         left join orders as failed on failed.goods_id = g.id and failed.status = 2 
group by `p`.`id`
order by total desc
limit 10

当查询时间范围较小时,查询速度较快,但当查询范围扩大时,查询速度极慢。

优化建议:

  1. 取消索引:删除 goods 表的 create_time 索引。
  2. 修改索引:将 orders 表的 goods_id 索引修改为 (create_time, goods_id, amount, status) 联合索引。
  3. 重写 sql优化后的 sql 如下:
SELECT g.title,
       COUNT(*)                       AS total,
       COALESCE(SUM(o.amount), 0)     AS total_amount,
       COALESCE(SUM(IF(o.status = 1, o.amount, 0)), 0)     AS success_amount,
       COALESCE(SUM(IF(o.status = 2, o.amount, 0)), 0)     AS failed_amount,
       COALESCE(SUM(o.status = 1), 0) AS success_total,
       COALESCE(SUM(o.status = 2), 0) AS failed_total
  FROM orders AS o
  JOIN goods AS g ON g.id = o.goods_id
 WHERE o.create_time BETWEEN 'xxx' AND 'yyy'
 GROUP BY o.id
 ORDER BY total DESC
 LIMIT 10

注:

由于数据量较小(商品数量:8000,订单数量:100000),考虑使用 sqlite 代替 mysql 进行查询,可以获得较好的性能。

以上就是如何优化 MySQL 商品销售情况统计查询性能,使其在查询时间范围扩大时也能保持快速响应?的详细内容,更多请关注其它相关文章!