Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

SQL Query to select parent that has child records with different values in the same column

This database has a one-to-many relationship where the parent table, Customers, is a list of customers and the child table, Orders, is a list of things they have bought. I'm trying to develop a query to select customers who have bought BOTH a television and a couch. The following query is returning 0 results.

SELECT Customer.*
FROM Customer
JOIN Orders
ON Customer.ID = Orders.customerID
WHERE Orders.item = 'television'
AND Orders.item = 'couch';

Replacing the AND with an OR doesn't work because it returns the customers who have bought both or just one of the items. My goal result is just the customers who have bought both.

like image 622
Matthew Blackburn Avatar asked Oct 29 '25 16:10

Matthew Blackburn


1 Answers

You need to leverage subqueries (or union) which flavor of sql are you using?

SELECT *
FROM CUSTOMER c
WHERE EXISTS (SELECT 1 FROM ORDERS o WHERE c.id = o.id and type = 'couch')
  and EXISTS (SELECT 1 FROM ORDERS o WHERE c.id = o.id and type = 'tv')
like image 180
discosammy Avatar answered Oct 31 '25 06:10

discosammy



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!