首页>itarticle>sql notes: leetcode#183 customers who never order
sql notes: leetcode#183 customers who never order
admin11月 12, 20200
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 |
+-----------+
Analysis
We can output customers whose id’s are not listed in the CustomerId of table Orders:
1
2
SELECTNameAS Customers FROM Customers WHEREIdNOTIN
(SELECT CustomerId FROM Orders);
Also, we can left join Customers table with Orders table. Then output customers whose order id is null:
1
2
3
SELECTNameAS Customers FROM Customers AS c
LEFTJOIN Orders AS o ON c.Id = o.CustomerId
WHERE o.Id ISNULL;
Solution
Solution 1
1
2
SELECTNameAS Customers FROM Customers WHEREIdNOTIN
近期评论