MySQL Query to find customers who have ordered two specific products

前端 未结 6 596
终归单人心
终归单人心 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 07:51

    SELECT COUNT(DISTINCT userId)
    FROM(
      SELECT userId
      FROM transactions
      WHERE product = 'PROD1'
      INTERSECT
      SELECT userId
      FROM transactions
      WHERE product = 'PROD2');
    

    The query creates two intermediate tables, one which contains userId of customer who bought PROD1 and another identical table for those who bought PROD2. The intersection operator returns a table which contains only rows found in both previous tables, i.e those who bought both products.

提交回复
热议问题