Reputation: 61
I have a question about how to retrieve data from one customer's order table (Oracle) like this:
id customer cake top
1 001 chocolate cream
2 002 chocolate jam
3 002 vanilla cream
4 003 banana cream
I want to know all orders from customers whose order includes chocolate cake.
The right result should be
id customer cake top
1 001 chocolate cream
2 002 chocolate jam
3 002 vanilla cream
I could do this by 2 separate queries in SQL, but is there any way to do this in a single query?
Many Thanks!
Upvotes: 2
Views: 52
Reputation: 1888
Something like this should work:
SELECT *
FROM customers
WHERE EXISTS (SELECT 1
FROM order_details
WHERE customers.id = order_details.customer_id
AND cake = 'chocolate');
Edited: added the chocolate cake condition.
Upvotes: 1
Reputation: 391
SELECT * FROM ORDER O1 WHERE EXISTS (
SELECT NULL FROM ORDER O2 WHERE O1.ID = O2.ID AND cake = 'chocolate'
)
You may try a variation of this subquery.
Upvotes: 0
Reputation: 12953
you should use an sub-query to get the customers:
select * from order where customer in (
select distinct customer from order where cake = 'chocolate'
)
Upvotes: 2
Reputation: 491
You can do this using inner queries.
SELECT * FROM ORDER WHERE CUSTOMER IN (
SELECT CUSTOMER FROM ORDER WHERE cake = 'chocolate'
)
Upvotes: 1
Reputation: 3548
A subquery that selects the distinct customers whose order include chocolate would work :
select
*
from
order
where
customer
in (select
distinct customer
from
order
where
cake = 'chocolate')
Upvotes: 1