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 | +-----------+
解题思路
将 Customers
和 Orders
表进行 左外连接, 其中 CustomerId
为 null
的行对应的客户就是没有下过订单的用户。
数据库在通过连接两张或多张表来返回记录时,都会生成一张中间的临时表,然后再将这张临时表返回给用户。
在使用LEFT OUTER JOIN
时,ON
和WHERE
条件的区别如下:
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