LeetCode: 183. Customers Who Never Order

本文介绍如何使用SQL查询找出从未下单的客户。通过左外连接Customers和Orders表,并筛选出CustomerId为null的行,即可得到所有未下单的客户名单。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

LeetCode: 183. Customers Who Never Order

题目描述

Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything.

Table: Customers.

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+

Table: Orders.

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+

Using the above tables as example, return the following:

+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+

解题思路

CustomersOrders 表进行 左外连接, 其中 CustomerIdnull 的行对应的客户就是没有下过订单的用户。

数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。
在使用 LEFT OUTER JOIN 时,ONWHERE 条件的区别如下:
1、ON 条件是在生成临时表时使用的条件,它不管 ON 中的条件是否为真,都会返回左边表中的记录。
2、WHERE 条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有 LEFT OUTER JOIN 的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。

AC 代码

SELECT Name AS Customers 
FROM Customers LEFT OUTER JOIN Orders
ON Customers.Id = Orders.CustomerId WHERE Orders.CustomerId is null
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值