随笔 - 384  文章 - 0  评论 - 0  阅读 - 13万

力扣1045(MySQL)-买下所有产品的客户(中等)

题目:

Customer 表:

 Product 表:

写一条 SQL 查询语句,从 Customer 表中查询购买了 Product 表中所有产品的客户的 id。

示例:

 

 解题思路:

建表语句:

1 create table if not exists customer_1045(customer_id int(3) not null, product_key int(3));
2 create table if not exists product_1045(product_key int(3));
3 truncate table customer_1045;
4 insert into customer_1045 values(1,5),(2,6),(3,5),(3,6),(1,6);
5 truncate table product_1045;
6 insert into product_1045 values(5),(6);

注意一下外键:

外键为某个表中的一列,它包含另一个表 的主键值,定义了两个表之间的关系。

1. Customer表中的一列是 product_key, product_key是Product表的主键;
2. 证明Customer表中的product_key 必定来自Product表;
3. 不存在:Customer中的product_key 不是 Product 表中的值。

1 select customer_id
2 from customer c
3 group by customer_id
4 having count(distinct c.product_key) = (select count(product_key) from product);

注意:

第一个distinct:如果一个用户能够重复购买同一个商品多次的话,比如(1,5)出现多次的话,就需要使用distinct去掉重复值;

第二个product_key前面不需要加distinct :product_key 是product的主键,故不会重复。

posted on   我不想一直当菜鸟  阅读(74)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 上周热点回顾(3.3-3.9)
历史上的今天:
2022-04-07 力扣442(java)-数组中重复的数据(中等)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示