183. 从不订购的客户
题目描述
某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。
Customers 表:
| Id | Name |
|---|---|
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
Orders 表:
| Id | CustomerId |
|---|---|
| 1 | 3 |
| 2 | 1 |
例如给定上述表格,你的查询应返回:
| Customers |
|---|
| Henry |
| Max |
实现
实现1
在Customers表中查找顾客,它的id不在Orders表的CustomerId中
select Name Customers
from Customers
where id not in(select CustomerId from Orders);
实现2
左连接,先左连接Customers和Orders表,on条件是顾客的id = orders表的CustomerId,生成一个顾客的id = orders表的CustomerId的临时表;where条件是临时表中取出Orders的id是NULL的客户。
select c.Name Customers
from Customers c left join Orders o
on c.Id = o.CustomerId
where o.Id IS NULL;
180

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



