题目:某网站包含两个表,Customers
表和 Orders
表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。
考点:多表查询之不在表内的数据
遇到要查找“不在表里的数据,也就是在表A里的数据,但是不在表B里的数据。”可以使用下图黑框里的sql语句。
注意:题目要求返回的列名为Customers
解题方案:
- LEFT JOIN 内连接
- NOT IN
LEFT JOIN:
#左连接方法
#注意:题目要求返回的列名为Customers
select c.Name Customers
from Customers c
left join Orders O
on c.Id = o.CustomerId
where o.CustomerId is null;
NOT IN:
#NOT IN 方法
#左连接方法
#注意:题目要求返回的列名为Customers
select c.Name Customers
from Customers c
where c.Id
not in(
select distinct o.CustomerId from Orders o
);