【SQL刷题系列】:leetcode183 Customers Who Never Order

▌刷题回顾web


【SQL刷题系列】:leetcode178 Rank Scores
app


▌题目描述ide


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查询语句找出全部没有任何订单的顾客。spa


Customers表:3d

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


Orders表:code

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+


使用上面两个表,你的查询结果应该与下面这样相同。orm

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


▌参考答案ci


参考1:leetcode

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的用户名字便可。

相关文章
相关标签/搜索