题目描述
某网站包含有两个表,Customers
表和Orders
表。编写一个SQL
查询,找出所有从不订购东西的客户。
Customers
表:
+----+-------+
| Id | Name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+
Orders
表:
+----+------------+
| Id | CustomerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+
例如给定上述的表格,你的查询应该返回:
+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+
算法设计与分析:
- 本题可以使用子查询和
not in
子句进行解决- 如果我们有一份曾经订过的客户名单,就很容易知道谁从未订购过。可以执行下面的这一句:
select customerid from orders;
,然后使用not in子句即可。
- 如果我们有一份曾经订过的客户名单,就很容易知道谁从未订购过。可以执行下面的这一句:
- 使用别名会使得程序执行速度变慢
# Write your MySQL query statement below
# 取别名会使得执行时间变慢
# 击败30%的人
# select
# c.name as Customers
# from
# Customers c
# where
# c.id not in
# (
# select CustomerId from Orders
# )
# 击败87%的人
select customers.name as 'Customers'
from customers
where customers.id not in
(
select customerid from orders
);