user4095519
user4095519

Reputation: 281

How can I speed up this MySQL query?

I have to optimize this query:

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')

This runs a while and I guess its because of the subselect. I know using a join here might speed it up, but I failed to make it work so far. Any ideas on how to speed that up?

Thanks!

Upvotes: 1

Views: 75

Answers (2)

Kickstart
Kickstart

Reputation: 21533

I would just do it as an extra level of join.

Something like this:-

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')

Assuming that you have an index on the sku field of the sales_flat_order_item table, an index on the entity_id on the sales_flat_order table and an index on the parent_id on the sales_flat_order_address table then this should be pretty quick.

Without indexes then pretty much any query will run very slowly.

Upvotes: 2

aphid
aphid

Reputation: 1163

Would adding INNER JOIN sales_flat_order_item ON sales_flat_order.entity_id = sales_flat_order_item.order_id and then using GROUP BY sfo.entity_id do the trick?

I'm assuming the table of sales order items has links to the orders those items belong to in order_id. You can then add the sku requirements to the outer query and get rid of the subquery. Providing you have proper indicing this might speed up your query.

Upvotes: 1

Related Questions