简体   繁体   中英

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!

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM