如何列出客户未购买的产品?

时间:2016-11-27 11:27:55

标签: sql ms-access

我有3个表格 - customerproductcustomerproduct(包含客户及其购买的产品的链接表)。
我想列出每个客户使用购买的产品。

示例

客户

Tom
Jim
Harry

产品

Shampoo
Brush
Shoe
Box

Customerproduct

Jim   | box
Jim   | brush
Tom   | brush
Harry | shampoo

所以,我的查询应显示:

Jim | shampoo
Jim | shoe
Tom | shampoo
Tom | shoe
Tom | box
...

我需要使用查找来获取我的客户和产品。制作单独的表CustomersandProducts表并手动提供它不是一个选项。 当然,必须有一种方法可以使用NOT EXISTS,NOT IN等获得结果吗?

1 个答案:

答案 0 :(得分:0)

首先,您需要产品加入客户和产品,以获得客户和产品的所有排列和组合。然后只需在实际的客户产品表中查找。

尝试以下查询:

select c.cname,p.pname
customers c,
product p
where c.name,p.name not in (
select cp_i.cname,cp_i.pname
from customerproduct cp_i)

如果任何表中的行数很高,则此查询将对资源非常敏感(cpu / io等)。

另一种方法:

select c.cname,p.pname
customers c,
product p
where not exists (
select 1
from customerproduct cp_i
where cp_i.cname=c.cname
and cp_i.pname=p.pname)
相关问题