MySQL数据透视表 - 不在

时间:2016-02-24 11:10:05

标签: mysql pivot-table

在MySQL数据库中,我有以下表格:

客户

CUSTOMER_ID | NAME
---------------------------
1           | John Doe
2           | Peter Jones
3           | David Smith

产品

PRODUCT_ID  | DESCRIPTION
---------------------------
1           | Toothbrush
2           | Shaving cream
3           | Deodorant

customer_product

CUSTOMER_ID | PRODUCT_ID
---------------------------
1           | 2
1           | 3
2           | 1
3           | 1
3           | 2

customer_product 是数据透视表。当客户订购产品时,它将被记录在那里。

我的问题是:我如何选择没有订购某种产品的所有客户?

例如,我想检索从未订购牙刷的所有客户。

2 个答案:

答案 0 :(得分:1)

您可以使用NOT EXISTS

SELECT CUSTOMER_ID,NAME
FROM customers AS c
WHERE NOT EXISTS (
   SELECT 1
   FROM customer_product AS cp
   INNER JOIN products AS p
      ON cp.PRODUCT_ID= p.PRODUCT_ID
   WHERE p.DESCRIPTION = 'Toothbrush' AND cp.CUSTOMER_ID = c.CUSTOMER_ID)

答案 1 :(得分:1)

这是另一种适合你的方式

select c.customer_id,c.Name from  customers c
where c.customer_id not in
(select c.customer_id from  customers c
left join customer_product cp on c.customer_id = cp.customer_id
inner join products p on cp.product_id = p.product_id
where p.description ='toothbrush'
) ;