0

I have a query in which I want to select all the customers who have orders with a particular product_id(say 12,13). I have made a fiddle for this. There is an orders table which contains the order_id and customer_id. Order_detail table has order_id and product_id. These are the sample tables. Original tables contain more than 30000 records. Could you please help me in optimising the queries or guide me the way to do so?

http://sqlfiddle.com/#!9/838da/3

2 Answers 2

1

You can use below final query-

SELECT customer_id,first_name 
FROM customer_detail cd 
JOIN orders ors ON cd.customer_id=ors.customer_id 
JOIN order_detail od ON od.order_id=ors.order_id 
WHERE product_id IN (12,13); 

Note: Below fields should be indexed - customer_id IN orders TABLE order_id AND product_id IN order_detail TABLE

Sign up to request clarification or add additional context in comments.

4 Comments

what if customers are repeated in orders ?
how can I create view of this in procedure so that I can use this for other joins to get data from other tables?
use group by customer_id at the end for multiple customers.
Please do NOT use GROUP BY or DISTINCT to get rid of double entries. Rather use a WHERE EXISTS construction. Performance wise it's night and day.
1
select c.* from customer_detail c 
inner join orders o on o.customer_id = c.customer_id
inner join order_detail od on od.order_id = o.order_id
where od.product_id in (12,13);

I think this is what you are looking for.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.