leetcode-183

183. 从不订购的客户

题目描述:

某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。

Customers 表:

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

Orders 表:

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

例如给定上述表格,你的查询应返回:

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

代码及解析:

利用左连接即可轻松解决,左连接保留左表,右表无数据则用NULL自动填充,所以左连接后,只需判断CustomerId 是否为NULL即可

1
2
3
4
5
6
7
# Write your MySQL query statement below

select Name Customers

from Customers a left join Orders b on a.Id = b.CustomerId

where b.CustomerId is NULL;
hey!baby,站住,点它!