【SQL刷题系列】:leetcode183 Customers Who Never Order
16lz
2021-01-22
▌刷题回顾
【SQL刷题系列】:leetcode178 Rank Scores
▌题目描述
Suppose that a website contains two tables, the Customers table and the Orders table. Write a SQL query to find all customers who never order anything.
假设一个网站包含两个表: 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:
select Name as Customers from Customers
where Id not in (select distinct CustomerId from Orders);
参考2:
select name AS Customers
from Customers LEFT JOIN Orders
ON Customers.Id=Orders.CustomerId
WHERE Orders.CustomerId IS NULL;
▌答案解析
参考1:通过查询select的嵌套使用。先在Orders表中返回所有有订单的客户Id,然后在Customer查询不在Orders表中的客户Id,最后返回相应的用户名字,即为最终结果。当然,也可以使用join通过连接两个表来实现
参考2:将Customers表的Id与Orders表的CustomerId建立左连接,那么Orders原本缺少的信息就会自动用NULL来代替。然后用where查询是NULL的用户名字即可。
更多相关文章
- Python有序字典的两个小“惊喜”~~
- Python 为什么只需一条语句“a,b=b,a”,就能直接交换两个变量?
- 图解 LeetCode 第 421 题:数组中两个数的最大异或值
- LeetCode数据库篇|175组合两个表
- php中比较两个数组差异的方法
- PHP如何计算两个时间段交集的天数?
- PHP 框架 Hyperf 实现处理超时未支付订单和延时队列
- php如何计算两个时间戳之间相差的日时分秒