0%

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.

1
2
3
4
5
6
7
8
+----+-------+
| Id | Name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+

Table: Orders.

1
2
3
4
5
6
+----+------------+
| Id | CustomerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+

Using the above tables as example, return the following:

1
2
3
4
5
6
+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+

子查询

先从Orders里面找出所有购买过东西的顾客id组成一个集合A, 然后再判断customer里的每个顾客是否在A中.

1
2
3
4
# Write your MySQL query statement below
SELECT Name AS Customers FROM Customers WHERE Id NOT IN (
SELECT DISTINCT CustomerId FROM Orders
);