我必须优化此查询:
SELECT DISTINCT
sfo.entity_id,
sfo.created_at,
sfoa.postcode,
sfo.customer_id
FROM sales_flat_order sfo
JOIN sales_flat_order_address sfoa
ON sfo.entity_id = sfoa.parent_id
WHERE sfo.entity_id IN (SELECT DISTINCT
order_id
FROM sales_flat_order_item
WHERE sku = 'whatever'
OR sku = 'whatever1')
这会运行一段时间,我猜它是因为subselect。我知道在这里使用连接可能会加快速度,但到目前为止我还没有成功。关于如何提高速度的任何想法?
谢谢!
答案 0 :(得分:2)
我只是将其作为额外的加入级别。
这样的事情: -
SELECT DISTINCT
sfo.entity_id,
sfo.created_at,
sfoa.postcode,
sfo.customer_id
FROM sales_flat_order sfo
INNER JOIN sales_flat_order_address sfoa
ON sfo.entity_id = sfoa.parent_id
INNER JOIN sales_flat_order_item sfoi
ON sfo.entity_id = sfoi.order_id
WHERE sku IN ('whatever', 'whatever1')
假设您在sales_flat_order_item表的sku字段上有索引,sales_flat_order表上的entity_id索引和sales_flat_order_address表上parent_id的索引,那么这应该非常快。
没有索引,几乎任何查询都会运行得很慢。
答案 1 :(得分:1)
添加INNER JOIN sales_flat_order_item ON sales_flat_order.entity_id = sales_flat_order_item.order_id
然后使用GROUP BY sfo.entity_id
会有效吗?
我假设销售订单商品表中包含指向这些商品属于order_id的订单的链接。然后,您可以将sku要求添加到外部查询并删除子查询。如果您有适当的指示,这可能会加快您的查询速度。