2009-11-04 106 views
2

我遇到了一個查詢,該查詢將查找已購買PROD1和PROD2的所有客戶。MySQL查詢以查找已訂購兩種特定產品的客戶

這裏是一個僞查詢那種看起來像什麼,我想做的事:(顯然這是行不通的)

SELECT COUNT(DISTINCT userid) 
    FROM TRANSACTIONS 
WHERE product_id = 'prod1' 
    AND product_id = 'prod2' 

所以基本上我想獲得不同數量的計數在transactions表中對於product_id'prod1'和'prod2'具有交易的用戶標識。每個交易都存儲在transactions表中的一行中。

回答

4

我做好以下方式這種類型的查詢:

SELECT COUNT(DISTINCT t1.userid) AS user_count 
    FROM TRANSACTIONS t1 
    JOIN TRANSACTIONS t2 USING (userid) 
WHERE t1.product_id = 'prod1' 
    AND t2.product_id = 'prod2'; 

GROUP BY解決方案shown通過@najmeddine也產生你想要的答案,但它並沒有對MySQL的執行,以及。 MySQL很難優化GROUP BY查詢。

您應該嘗試這兩個查詢,分析EXPLAIN的優化,並運行一些測試並計算給定數據量的結果。

+0

完全正確法案 – Ian 2009-11-04 22:45:10

4
SELECT userid 
    FROM TRANSACTIONS 
WHERE product_id in ('prod1', 'prod2') 
GROUP BY userid 
HAVING COUNT(DISTINCT product_id) = 2 
2

(由下面的使用由用戶提供的附加信息的新選項)

嘗試

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) 

或者

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

或者

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

或者

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

這是一個基於臭名昭著的羅斯文示例數據庫的訪問答案。你應該很容易在mySql中翻譯它。

SELECT o.CustomerID, Sum([ProductID]='Prod1') AS Expr1, Sum([productid]='Prod1') AS Expr2 
FROM Orders AS o INNER JOIN [Order Details] AS d ON o.OrderID = d.OrderID 
GROUP BY o.CustomerID 
HAVING (((Sum([ProductID]='Prod1'))<>0) AND ((Sum([productid]='Prod1'))<>0)); 
0
SELECT COUNT(DISTINCT userId) 
FROM(
    SELECT userId 
    FROM transactions 
    WHERE product = 'PROD1' 
    INTERSECT 
    SELECT userId 
    FROM transactions 
    WHERE product = 'PROD2'); 

查詢創建兩個中間表,其中一個包含客戶誰買PROD1和另一個相同的表對於那些誰買Prod2的的用戶ID。 交集操作符返回一個只包含前兩個表中找到的行的表,即那些購買了這兩種產品的表。

0

舉例sakila的DB:

SELECT R.customer_id, GROUP_CONCAT(I.film_id) 
FROM sakila.rental R 
RIGHT OUTER JOIN sakila.inventory I ON R.inventory_id = I.inventory_id 
WHERE I.film_id IN (22,44) GROUP BY R.customer_id HAVING COUNT(*) = 2 
相關問題