likes
comments
collection
share

数据库每日一题---第4天:从不订购的客户

作者站长头像
站长
· 阅读数 4

一、问题描述

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

题目链接:从不订购的客户

二、题目要求

样例

Customers 表:
+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+
Orders 表:

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+
例如给定上述表格,你的查询应返回:

+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+

考察

1.子查询、左连接
2.建议用时10~25min

三、问题分析

1.子查询

这一题两个表的Id其实是不一样的,含义也不同。而Customers 表中的IdOrders 表中的 CustomerId含义是相同的。

所以,这一题的思路就变得很清晰了。我们只需要找出在Customers 表出现的Id却没有在Orders 表中的 CustomerId中出现过就行。

2.左连接

左连接就是优先输出左表的所有记录,而只返回右表与对应的条件相等的数据,以这题为例,左连接的结果应该是:

+----+-------++-----------+
| Id | Name  || Id | CustomerId |    
+----+-------++----+------------+
| 1  | Joe   || 1     | 3          |
| 2  | Henry || 2     | 1          |
| 3  | Sam   || null  | null       |
| 4  | Max   || null  | null       |

如上表所示,左侧的数据全部输出而右表只输出符合条件的结果,我们只需要通过Id号将两个表连接起来,然后判断右侧的Id号是否为空就行了。

附录:

  • 右连接

    右连接和左连接一样,输出全部的右表数据却只输出符合条件的左表数据,不符合条件置为空。

  • 内连接

    匹配两个表中同时符合条件的数据

四、编码实现

1.子查询

select c.Name as 'Customers'
from Customers as c
where c.Id not in( select CustomerId from Orders)

2.左连接

select c.Name as 'Customers'
from Customers c
left join Orders o on o.CustomerId=c.Id where o.Id is null

五、测试结果

数据库每日一题---第4天:从不订购的客户

数据库每日一题---第4天:从不订购的客户

数据库每日一题---第4天:从不订购的客户