mysql商品销售情况统计查询特别慢,如何优化呢?

新手上路,请多包涵

问题描述

goods

字段类型说明
id主键递增主键
titlevarchar商品名称
create_timeint64创建时间(索引)

orders

字段类型说明
id主键递增主键
goods_idint64商品id(索引)
amountdecimal金额
statustinyint状态 0:进行中,1:已成功,2:已失败(索引)
create_timeint64创建时间(索引)
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

查询结果

totaltotal_amountsuccess_totalfailed_totalsuccess_amountfailed_amount
订单总数量订单总金额成功的订单数量失败的订单数量成功的订单金额失败的订单金额

商品数量:8000个左右
订单数量:100000左右

以上sql是可以查询出来的 但是查询当天的还可以(300-500ms左右),查询昨天,本周,上周,本月,上月,以及本季度,上季度,今年,以及去年和全部的时候,特别的慢,

有想过用clickhouse 但是比较麻烦,要涉及到数据同步

请教下 如何优化sql达到目的呢?

阅读 2.5k
1 个回答

建议尝试:

  1. 去掉俩表的 create_time 索引
  2. orders 表的 goods_id 索引改成 (create_time, goods_id, amount, status)
  3. 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

就几十万的数据量,感觉换 SQLite 来查询,应该都没啥性能问题

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏