[LeetCode] 183. Customers Who Never Order

Problem

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       |
+-----------+

Explanation

  1. We can use the Customers table LEFT JOIN the Orders table, and match their Id, and where Orders.Id is NULL.

Solution

1
2
3
4
5
6
# Write your MySQL query statement below
SELECT c1.Name as Customers
FROM Customers as c1
LEFT JOIN Orders as o1
ON c1.Id = o1.CustomerId
WHERE o1.Id is NULL;