LeetCode183從不訂閱的客戶

題目:

某網站包含兩個表,Customers 表和 Orders 表。編寫一個 SQL 查詢,找出所有從不訂購任何東西的客戶。

Customers 表:

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

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+
例如給定上述表格,你的查詢應返回:

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

 思路一:進行左連接,然後取Id爲空的

select Name as Customers from Customers c left join Orders o on c.Id=o.CustomerId where o.Id is NULL

注意:不能寫o.Id=null.

思路二:先在Orders中查詢CustomerId,再在Customers中查Id不在CustomerId的範圍的數

select Name as Customers from Customers c where c.Id not in(select o.CustomerId from Orders o)

 

發佈了105 篇原創文章 · 獲贊 2 · 訪問量 1989
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章