SQL架构
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')
题目描述:
某网站包含两个表,Customers
表和 Orders
表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。
Customers
表:
+----+-------+
| Id | Name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+
Orders
表:
+----+------------+
| Id | CustomerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+
根据以上输入,你的查询应返回以下结果:
+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+
解法
思路:要找出从不订购的用户,从不订购的用户指没有出现在Orders
表中的用户,那么也就是说只要筛选出不在Orders
表中的数据就好。
方法1:使用 NOT IN + 子查询
SELECT c.Name AS Customers
FROM Customers AS c
WHERE c.Id NOT IN(
SELECT CustomerId FROM Orders
)
耗时:113ms
方法2:使用LEFT JOIN
SELECT c.Name as Customers
FROM Customers AS c
LEFT JOIN Orders AS o
ON c.Id = o.CustomerId
WHERE o.Id IS NULL
耗时:163ms