I’m using the query below is a report that runs incredibly slow (due to the subselect I’m sure). I’ve tried splitting this into 2 separate queries where I find the value for num_orders inside my application loop, however it runs just about as slow. The problem here is my report uses a date range, however within each result, I need to know if a customer had more than 1 total orders where recurring_order
= ‘1’ and rec_denied
= ‘0’ (which tells the user if they are a NEW recurring order customer or not) outside the date range.
SELECT c.cust_id,
(
SELECT COUNT(o1.order_customer_id)
FROM orders AS o1
LEFT JOIN order_products AS op1 ON o1.order_id = op1.order_id AND op1.recurring_order = '1' AND op1.rec_denied = '0'
WHERE o1.order_customer_id = c.cust_id
GROUP BY o1.order_customer_id
) AS num_orders
FROM customers AS c
LEFT JOIN orders AS o ON c.cust_id = o.order_customer_id
LEFT JOIN order_products AS op ON o.order_id = op.order_id AND op.recurring_order = '1' AND op.rec_denied = '0'
WHERE o.order_created_date >= '2010-10-01' AND
o.order_created_date <= '2010-10-30'
GROUP BY c.cust_id
Any suggestions on optimizing this?