[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);

 

參考資料:

https://leetcode.com/discuss/22624/three-accepted-solutions

https://leetcode.com/discuss/53213/a-solution-using-not-in-and-another-one-using-left-join

 

LeetCode All in One 題目講解匯總(持續更新中...)


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM