我有这个 SQL 查询,可以让我知道客户何时订购了某种产品:
SELECT * FROM ps_customer c
INNER JOIN ps_orders o ON (c.id_customer=o.id_customer)
INNER JOIN ps_order_detail od ON(od.id_order=o.id_order)
WHERE od.product_id=1
我希望获得订购产品 1、2、3 的客户,但绝不订购 4。
我不能简单地创建
WHERE od.product_id IN (1, 2, 3) AND od.product_id != 4
,但我一直在思考如何正确构建该查询。
仅供参考,数据库结构是基本的 Prestashop (1.6.1.4) 数据存储。
这是 SQLFiddle : http://sqlfiddle.com/#!9/dfd65
(我无法添加数据,对于 SQLFiddle 来说太多了......)
也许你应该有不同的想法
SELECT * FROM ps_customer c
INNER JOIN ps_orders o ON (c.id_customer=o.id_customer)
INNER JOIN ps_order_detail od ON(od.id_order=o.id_order)
WHERE od.product_id IN (1, 2, 3) and c.id_customer NOT IN (select id_customer from ps_orders where product_id IN (4) )
您可以在 id_customer 上使用几个 dinaminc 表连接
select * from (
SELECT id_customer
FROM ps_customer c
INNER JOIN ps_orders o ON c.id_customer=o.id_customer
INNER JOIN ps_order_detail od ON od.id_order=o.id_order
WHERE od.product_id <> 4 ) t1
INNER JOIN (
SELECT id_customer FROM ps_customer c
INNER JOIN ps_orders o ON c.id_customer=o.id_customer
INNER JOIN ps_order_detail od ON od.id_order=o.id_order
WHERE od.product_id in ( 1,2,3)
having count(distinct(od.product_id)) =3
) t2 on t1.id_customer = t2.id_customer