sql - 两个表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
解决方案
使用聚合:
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;
推荐阅读
- python - 在python问题的dict中保存多行
- r - 消除 ggplot 折线图中的 X 轴间隙
- android - 在 Android Studio 上评估表达式时出现问题
- php - Roundcube 自定义 SMTP_USER 变量
- excel - 添加 PowerQuery 时如何使用字符串作为源
- android - AndroidRuntime:致命异常:AsyncTask #1 进程
- sql - 为“aa”多次指定了“PATIENT_ID”列
- kotlin-multiplatform - kotlin-multiplatform 时间戳以毫秒为单位(unix 时间)
- c# - 我的 .exe 在其他计算机上打开和关闭
- c# - Parse 方法抛出异常