选择满足不同记录中许多条件的列

时间:2018-11-16 08:59:23

标签: mysql select

我有这样的桌子:

+----------+---------+
| Customer | Product |
+----------+---------+
|        1 |       1 |
|        1 |       2 |
|        1 |       3 |
|        2 |       1 |
|        2 |       2 |
|        2 |       2 |
+----------+---------+

我想选择购买商品1 AND 2 AND 3的客户。因此我的查询应返回1。如何实现?

2 个答案:

答案 0 :(得分:3)

如果您希望购买了全部3种产品的客户,则可以使用汇总功能count(distinct product)

    SELECT Customer
    FROM your_table
    where product in (1,2,3)
    GROUP BY Customer
    HAVING count(distinct product) = 3

答案 1 :(得分:2)

您可以在GROUP BYCustomer,并在Having子句中使用基于条件聚合的过滤。在数字上下文中使用时,MySQL自动将布尔值转换为0/1。

为了让Product购买特定的Customer,其SUM(Product = ..)应该为 1


案例1:吸引那些至少购买了1,2,3产品之一的客户(他们可能也购买了其他产品)。

SELECT Customer
FROM your_table
GROUP BY Customer
HAVING SUM(Product = 1) AND -- 1 should be bought
       SUM(Product = 2) AND -- 2 should be bought
       SUM(Product = 3)     -- 3 should be bought

如果您想要排他性,即 ,那么客户除了1,2,3之外没有购买其他任何产品;那么您可以改用以下内容。

案例2:吸引那些只购买了 1,2,3种产品且至少购买一次的客户。

SELECT Customer
FROM your_table
GROUP BY Customer
HAVING SUM(Product = 1) AND  -- 1 should be bought
       SUM(Product = 2) AND  -- 2 should be bought
       SUM(Product = 3) AND  -- 3 should be bought
       NOT SUM(Product NOT IN (1,2,3))  -- anything other 1,2,3 should not be bought