登录
首页 >  数据库 >  MySQL

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

时间:2024-12-07 16:09:45 222浏览 收藏

怎么入门数据库编程?需要学习哪些知识点?这是新手们刚接触编程时常见的问题;下面golang学习网就来给大家整理分享一些知识点,希望能够给初学者一些帮助。本篇文章就来介绍《如何优化 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 商品销售情况统计查询性能,使其在查询时间范围扩大时也能保持快速响应?》的介绍就到此结束啦,但是学无止境,想要了解学习更多关于数据库的相关知识,请关注golang学习网公众号!

相关阅读
更多>
最新阅读
更多>
课程推荐
更多>