0

I've got a table for storing customers choices regarding products.

It stores a customer number, product number and whether it's a yes or no thanks on the product. We're storing yes/no because the customer must make a choice on all products so that we can check if they've made all choices.

Customer | Product | Status
---------------------------
12345    | 1       | 0
12345    | 2       | 1
12345    | 3       | 1
12345    | 4       | 0
12345    | 5       | 1
23456    | 1       | 1
23456    | 2       | 0
23456    | 3       | 1
23456    | 4       | 1
23456    | 5       | 0

What I want to do is check which customers has chosen a specific set of products. That could be something like select * from choices where product = 1 and product = 3 group by customer but then I must also query products with status = 1

Is there a way to solve this in a query or will I have to resort to a couple of calls to some PHP?

4

2 回答 2

3
select customer 
from choices 
where status = 1 and product in (1,3)
group by customer
having count(distinct product) = 2
于 2013-09-30T09:45:53.183 回答
0
SELECT DISTINCT a.customer
FROM choices a, choices b
WHERE a.customer = b.customer
AND a.product = 1
AND b.product = 3;

这样做还可以让您稍后放入更复杂的逻辑:如果您希望每个人在 2012 年购买产品 1,在 2013 年购买产品 2,您可以在 where 子句中添加额外的条件来过滤这些人。

于 2013-09-30T10:13:48.893 回答