MySQL Query to find customers who have ordered two specific products

前端 未结 6 593
终归单人心
终归单人心 2021-01-14 07:21

I\'m having trouble coming up with a query that will find all customers who have purchased both PROD1 and PROD2.

Here\'s a pseudo-query that kind of looks like what

6条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2021-01-14 08:00

    (Added new options below using the additional information provided by the user)

    Try

    SELECT * FROM Customers WHERE 
     EXISTS (SELECT * FROM Purchases WHERE ProductID = 'PROD1' AND CustID = Customers.CustID)
     AND
     EXISTS (SELECT * FROM Purchases WHERE ProductID = 'PROD2' AND CustID = Customers.CustID)
    

    Or

    SELECT * FROM Customers WHERE 
     CustID IN (SELECT CustID FROM Purchases WHERE ProductID = 'PROD1')
     AND
     CustID IN (SELECT CustID FROM Purchases WHERE ProductID = 'PROD2')
    

    Or

    SELECT UserID FROM Transactions WHERE ProductID = 'PROD1'
     AND EXISTS (SELECT * FROM Transactions WHERE UserID = T1.UserID 
      AND ProductID = 'PROD2')
    

    Or

    SELECT UserID FROM Transactions WHERE ProductID = 'PROD1'
     AND UserID IN (SELECT UserID FROM Transactions WHERE ProductID = 'PROD2')
    

提交回复
热议问题