简体   繁体   中英

Mysql: Multiple where query

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?

select customer 
from choices 
where status = 1 and product in (1,3)
group by customer
having count(distinct product) = 2
SELECT DISTINCT a.customer
FROM choices a, choices b
WHERE a.customer = b.customer
AND a.product = 1
AND b.product = 3;

Doing this also allows you to put more complicated logic in later on: if you wanted everyone who purchased product 1 in 2012, and product 2 in 2013, you can add extra conditions in the where clause to filter for those.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM