首页 > 解决方案 > 两个表JOIN

问题描述

我正在努力提高我的 SQL 技能,但这真的不容易。当我认为我有所改进时,我遇到了一个基本的 SQL 问题,我无法继续前进。我有两张桌子。他们唯一的共同点是“订单”列。我想选择一个同时拥有这两种产品的客户(无论他/她是否在一个订单或多个订单中购买了这些产品)。在我的例子中,这个客户不是。345:

在此处输入图像描述

我的代码看起来像这样,但它并没有真正解决我的问题,因为它列出了购买一种产品或两种产品的人:

select t2.client, t1.product, t1.order
from table_1 t1
join table_2 t2 on t1.order = t2.order
where product in ('a', 'b')
order by t2.client

标签: sql

解决方案


使用聚合:

select t2.client
from table_1 t1 join
     table_2 t2
     on t1.order = t2.order
where t1.product in ('a', 'b')
group by t2.client
having count(distinct t1.product) = 2;

推荐阅读