Leetcode 183. Customers Who Never Order
183. Customers Who Never Order
原题目链接:183. Customers Who Never Order
假设一个网站包含两张表,Customers顾客表和Orders订单表。写一条SQL查询语句找出所有从来没有下过单的客户。
Table: Customers
+----+-------+ | Id | Name | +----+-------+ | 1 | Joe | | 2 | Henry | | 3 | Sam | | 4 | Max | +----+-------+
Table: Orders
+----+------------+ | Id | CustomerId | +----+------------+ | 1 | 3 | | 2 | 1 | +----+------------+
将以上表格作为例子,返回以下数据:
+-----------+ | Customers | +-----------+ | Henry | | Max | +-----------+
Solution
方法:采用子查询和NOT IN语句[Accepted]
Algorithm
反过来,如果我们有一个下过订单的客户列表,那么了解谁从来没有下过订单将很容易。我们可以采用下面的代码获得这一的列表。
1 | SELECT customerid FROM orders; |
然后,我们可以使用NOT IN来查询不在这个列表当中的客户。
MySQL
1 | SELECT customers.name AS Customers |