我有一个表格,用于存储客户对产品的选择。
它存储客户编号,产品编号以及产品上的是或否感谢。我们存储是/否,因为客户必须对所有产品做出选择,以便我们可以检查他们是否做出了所有选择。
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
我想做的是检查哪些客户选择了一组特定的产品。这可能是类似select * from choices where product = 1 and product = 3 group by customer
但随后我还必须查询产品status = 1
有没有办法在查询中解决这个问题,或者我将不得不求助于对一些 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;
这样做还可以让你在以后加入更复杂的逻辑:如果你想要在 2012 年购买产品 1 和在 2013 年购买产品 2 的每个人,你可以在 where 子句中添加额外的条件来过滤这些条件。