優化 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
當查詢時間范圍較小時,查詢速度較快,但當查詢范圍擴大時,查詢速度極慢。
優化建議:
- 取消索引:刪除 goods 表的 create_time 索引。
- 修改索引:將 orders 表的 goods_id 索引修改為 (create_time, goods_id, amount, status) 聯合索引。
- 重寫 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 進行查詢,可以獲得較好的性能。
? 版權聲明
文章版權歸作者所有,未經允許請勿轉載。
THE END