题53:
根据下面两个表写一条 SQL 查询语句,从 Customer 表中查询购买了 Product 表中所有产品的客户的 id。

其中:
- Customer表:product_key 此表的外键;
- Product表:product_key 是此表的主键。
解题思路:
因为product_key 是 Customer表的外键,因此不存在在于第一个表而不存在于第二个表。
(1)分组,COUNT(DISTINCT A.Product_Key)去重得到每个用户买了多少个商品;
(2)如果去重后的买的商品数据和Product数量一致即可。
select customer_id
from Customer
group by customer_id
having count(distinct product_key) in
(select count(distinct product_key) from Product);
该博客介绍了一个SQL查询问题,目标是从Customer表中检索购买了Product表中所有产品的客户ID。通过使用GROUP BY和HAVING子句,结合COUNT(DISTINCT product_key)与Product表的数量比较,可以找到满足条件的客户。
2273

被折叠的 条评论
为什么被折叠?



