LeetCode每天一题

183. 从不订购的客户

题目:

183. 从不订购的客户

难度简单160

SQL架构

某网站包含两个表,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 |
+-----------+

通过次数71,756

提交次数106,987

解题思路

这一题还是很简单的,第一次看的时候发现,这一题不就是多表查询吗?

思路:先查出订购东西的用户,在这个基础上取反就可以了。

1.连接查询可以吗?我们试试:

使用连接查询的theta方式:该方式通过where子句指定条件进行连接

我们先查询订购东西的用户

1
2
3
select c.Name as Customers
from Customers as c,Orders as o
where c.Id=o.CustomerId;

接下来如何取反呢?

这个还真不知道耶!

c.Id != o.CustomerId?

这个不行!

where not(c.Id=o.CustomerId)?

这个也不行!

如果大家有方法,请留言哦!

2.嵌套查询

先使用嵌套查询来先查询订购东西的用户

1
2
3
4
5
6
select Name as Customers
from Customers
where Id in
(select CustomerId
from Orders
);

接下来如何取反呢?

使用not in即可

1
2
3
4
5
6
select Customers.Name as Customers
from Customers
where Customers.Id not in(
select CustomerId
from Orders
);

答案解析

1
2
3
4
5
6
7
# Write your MySQL query statement below
select Customers.Name as Customers
from Customers
where Customers.Id not in(
select CustomerId
from Orders
);
点击查看
-------------------本文结束 感谢您的阅读-------------------