46,SQL训练之,力扣,183. 从不订购的客户

  • 学习:知识的初次邂逅
  • 复习:知识的温故知新
  • 练习:知识的实践应用

目录

一,原题力扣链接

二,题干

三,建表语句

四,分析

思路一,用自连接

思路二,用子查询 

五,SQL解答

解法一,左连接+条件判断is null

解法二,子查询 not in

六,验证

七,知识点总结


一,原题力扣链接

. - 力扣(LeetCode)

二,题干

Customers 表:

+-------------+---------+
| Column Name | Type    |
+-------------+---------+
| id          | int     |
| name        | varchar |
+-------------+---------+
在 SQL 中,id 是该表的主键。
该表的每一行都表示客户的 ID 和名称。

Orders 表:

+-------------+------+
| Column Name | Type |
+-------------+------+
| id          | int  |
| customerId  | int  |
+-------------+------+
在 SQL 中,id 是该表的主键。
customerId 是 Customers 表中 ID 的外键( Pandas 中的连接键)。
该表的每一行都表示订单的 ID 和订购该订单的客户的 ID。

找出所有从不点任何东西的顾客。

以 任意顺序 返回结果表。

结果格式如下所示。

示例 1:

输入:
Customers table:
+----+-------+
| id | name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+
Orders table:
+----+------------+
| id | customerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+
输出:
+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+

三,建表语句

Create table If Not Exists Customers (id int, name varchar(255));
Create table If Not Exists Orders (id int, customerId int);
Truncate table Customers;
insert into Customers (id, name) values ('1', 'Joe');
insert into Customers (id, name) values ('2', 'Henry');
insert into Customers (id, name) values ('3', 'Sam');
insert into Customers (id, name) values ('4', 'Max');
Truncate table Orders;
insert into Orders (id, customerId) values ('1', '3');
insert into Orders (id, customerId) values ('2', '1');

四,分析

题解:

第一张表:客户表

字段:客户di,客户名称

第二张表:订单表

字段:订单id,客户名称

要求: 从不订购的顾客

分析

从不订购的客户,那么就是在订单表没有出现的客户id

思路一,用自连接

第一步,连接2个表,用左连接

        客户表 左连接 订单表  条件 客户表的id 等于订单表的客户id;

第二步,做判断,当订单表的订单id是null的时候 求客户表的 name

第三步,取个别名

思路二,用子查询 

 第一步,客户表的客户id not in 订单表的客户id

        拿到 客户表的id 和姓名

第二步,提取姓名,更改别名

五,SQL解答

解法一,左连接+条件判断is null

-- 自联结查询
select name as Customers 
from customers c left join orders o on c.id=o.customerId
where o.id is null;

解法二,子查询 not in

-- 换子查询写法
select name as Customers  
from customers where id not in (select customerId from orders);

 

六,验证

 

七,知识点总结

  • 左连接练习
  • 子查询练习
  • is null 条件判断练习
  • not in 条件判断练习
  • as 取别名 练习

  • 学习:知识的初次邂逅
  • 复习:知识的温故知新
  • 练习:知识的实践应用

  • 7
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值