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