优化每月购买次数的SQL脚本

时间:2018-10-28 17:04:17

标签: mysql sql

我一直在徘徊以下查询是否有更优化的解决方案:

select count(purchases.id)
from purchases right join purchase_items on purchases.item_id=purchase_items.id
where purchases.created_date >= '2017-06-01'
and purchases.created_date < '2017-07-01'
and purchases.cancellation_date is null
and purchases.pending = 0;

谢谢!

1 个答案:

答案 0 :(得分:1)

使用内部联接并添加索引:

select count(*)
from purchases p join
     purchase_items pi
     on p.item_id = pi.id
where p.created_date >= '2017-06-01' and
      p.created_date < '2017-07-01' and
      p.cancellation_date is null and
      p.pending = 0;

purchases(pending, cancellation_date, created_date, item_id)purchase_items(id)上建立索引将有助于此查询。