每天一道SQL题
每天一道SQL题之day08
1、题目:
链接: 从不订购的客户
表: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 |
2、题解
select cus.name as Customers
from Customers cus
left join
Orders ord
on
cus.id = ord.customerId
where ord.id is null
3、解析
问题:一开始是想用左连接,觉得左连接用Customers
去连接Orders
表,判断条件是cus.id = ord.customerId
,具有对应订单的客户和订单匹配在一起,结果却不对。
看了一下别人的正确答案才发现是少了where ord.id is null
。那为什么则思考为什么要加这个判断条件呢?
由于左连接是保留左表的所有记录,并且如果没有匹配的右表记录,相关字段会被设置为null,因此,对于没有对应订单的客户,“Orders"表的相关字段(如"ord.id”)在左连接结果中将会是null。
通过"where ord.id is null",我们可以筛选出"Orders"表中没有对应订单的客户,即没有订单记录的客户。故这个筛选条件可以用来找出尚未下过订单的客户。