SQL實(shí)現(xiàn)LeetCode(183.從未下單訂購的顧客)
[LeetCode] 183.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 |
+-----------+
這道題讓我們給了我們一個(gè)Customers表和一個(gè)Orders表,讓我們找到從來沒有下單的顧客,那么我們最直接的方法就是找沒有在Orders表中出現(xiàn)的顧客Id就行了,用Not in關(guān)鍵字,如下所示:
解法一:
SELECT Name AS Customers FROM Customers WHERE Id NOT IN (SELECT CustomerId FROM Orders);
或者我們也可以用左交來聯(lián)合兩個(gè)表,只要找出右邊的CustomerId為Null的顧客就是木有下單的:
解法二:
SELECT Name AS Customers FROM Customers LEFT JOIN Orders ON Customers.Id = Orders.CustomerId WHERE Orders.CustomerId IS NULL;
我們還可以用Not exists關(guān)鍵字來做,原理和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
到此這篇關(guān)于SQL實(shí)現(xiàn)LeetCode(182.從未下單訂購的顧客)的文章就介紹到這了,更多相關(guān)SQL實(shí)現(xiàn)從未下單訂購的顧客內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
- SQL實(shí)現(xiàn)LeetCode(196.刪除重復(fù)郵箱)
- SQL實(shí)現(xiàn)LeetCode(185.系里前三高薪水)
- SQL實(shí)現(xiàn)LeetCode(184.系里最高薪水)
- SQL實(shí)現(xiàn)LeetCode(182.重復(fù)的郵箱)
- SQL實(shí)現(xiàn)LeetCode(181.員工掙得比經(jīng)理多)
- SQL實(shí)現(xiàn)LeetCode(180.連續(xù)的數(shù)字)
- C++實(shí)現(xiàn)LeetCode(179.最大組合數(shù))
- SQL實(shí)現(xiàn)LeetCode(197.上升溫度)
相關(guān)文章
Linux上通過binlog文件恢復(fù)mysql數(shù)據(jù)庫詳細(xì)步驟
binglog文件是服務(wù)器的二進(jìn)制日志記錄著該數(shù)據(jù)庫的所有增刪改的操作日志,接下來通過本文給大家介紹linux上通過binlog文件恢復(fù)mysql數(shù)據(jù)庫詳細(xì)步驟,非常不錯(cuò),需要的朋友參考下2016-08-08連接mysql連接超時(shí)報(bào)錯(cuò)問題以及解決
這篇文章主要介紹了連接mysql連接超時(shí)報(bào)錯(cuò)問題以及解決方案,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-11-11MySQL數(shù)據(jù)庫定時(shí)備份的實(shí)現(xiàn)方法
這篇文章主要介紹了MySQL數(shù)據(jù)庫的定時(shí)備份的相關(guān)知識(shí),非常不錯(cuò),具有一定的參考借鑒價(jià)值,需要的朋友可以參考下2019-04-04