题目描述
某网站包含有两个表,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
);

本文介绍如何使用SQL查询从两个表中找出从未订购商品的客户。通过子查询和notin子句,结合Customers和Orders表,筛选出特定条件的客户名单。
1637

被折叠的 条评论
为什么被折叠?



