[LeetCode] Customers Who Never Order 从未下单订购的顾客

简介:

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.

Table: Customers.

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

Table: Orders.

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

Using the above tables as example, return the following:

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

这道题让我们给了我们一个Customers表和一个Orders表,让我们找到从来没有下单的顾客,那么我们最直接的方法就是找没有在Orders表中出现的顾客Id就行了,用Not in关键字,如下所示:

解法一:

SELECT Name AS Customers FROM Customers 
WHERE Id NOT IN (SELECT CustomerId FROM Orders);

或者我们也可以用左交来联合两个表,只要找出右边的CustomerId为Null的顾客就是木有下单的:

解法二:

SELECT Name AS Customers FROM Customers
LEFT JOIN Orders ON Customers.Id = Orders.CustomerId
WHERE Orders.CustomerId IS NULL;

我们还可以用Not exists关键字来做,原理和Not in很像,参见代码如下:

解法三:

SELECT Name AS Customers FROM Customers c
WHERE NOT EXISTS (SELECT * FROM Orders o WHERE o.CustomerId = c.Id);

本文转自博客园Grandyang的博客,原文链接:从未下单订购的顾客[LeetCode] Customers Who Never Order ,如需转载请自行联系原博主。

相关文章
|
8月前
|
SQL
leetcode-SQL-1398. 购买了产品 A 和产品 B 却没有购买产品 C 的顾客
leetcode-SQL-1398. 购买了产品 A 和产品 B 却没有购买产品 C 的顾客
44 1
|
8月前
|
SQL
leetcode-SQL-1581. 进店却未进行过交易的顾客
leetcode-SQL-1581. 进店却未进行过交易的顾客
59 0
LeetCode 429. N-ary Tree Level Order Traversal
给定一个 N 叉树,返回其节点值的层序遍历。 (即从左到右,逐层遍历)。
91 0
LeetCode 429. N-ary Tree Level Order Traversal
|
存储
LeetCode 107. Binary Tree Level Order Traversal II
给定二叉树,返回其节点值的自下而上级别顺序遍历。 (即,从左到右,逐下而上)。
84 0
LeetCode 107. Binary Tree Level Order Traversal II
|
Python
LeetCode 103. BTree Zigzag Level Order Traversal
给定二叉树,返回其节点值的Z字形级别遍历。 (即,从左到右,然后从右到左进行下一级别并在之间交替)。
80 0
LeetCode 103. BTree Zigzag Level Order Traversal
|
存储
LeetCode 102. 二叉树的层序遍历 Binary Tree Level Order Traversal
LeetCode 102. 二叉树的层序遍历 Binary Tree Level Order Traversal
LeetCode contest 183 5376. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
LeetCode contest 183 5376. 非递增顺序的最小子序列 Minimum Subsequence in Non-Increasing Order
|
数据库
LeetCode(数据库)- Drop Type 1 Orders for Customers With Type 0 Orders
LeetCode(数据库)- Drop Type 1 Orders for Customers With Type 0 Orders
111 0
|
数据库
LeetCode(数据库)- 每位顾客最经常订购的商品
LeetCode(数据库)- 每位顾客最经常订购的商品
126 0