1. 程式人生 > 實用技巧 >git fetch和pull詳解

git fetch和pull詳解

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

Customers 表:

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


Orders 表:

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


例如給定上述表格,你的查詢應返回:

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

解法一:

# Write your MySQL query statement below
select Name as Customers from Customers where Id not in (select CustomerId from Orders)

解法二:比解法一效率高

# Write your MySQL query statement below
select Name as Customers from Customers where
not exists (select CustomerId from Orders where Orders.CustomerId = Customers.Id)

備註:

not in存在隱患,如果查詢的CustomerId為 null 時,就會查詢結果錯誤。

not exists 可避免not in上面問題

解法三:連線

# Write your MySQL query statement below
select Name as Customers from Customers as a left join Orders as b on a.Id = b.CustomerId where
b.Id is null

做連線後表如下,然後做篩選。便於理解。

Id
Name
Id
CustomerId
1
Joe
2 1
2
Henry
null null
3
Sam
1 3
4
Max
null null