某網站包含兩個表,Customers 表和 Orders 表。編寫一個 SQL 查詢,找出所有從不訂購任何東西的客戶。
Customers 表:
+----+-------+
| Id | Name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+
Orders 表:
+----+------------+
| Id | CustomerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+
即是查找ID不在orders表中的客戶名。
語句
子查詢+IN
select name Customers from Customers where id not in (select CustomerId from Orders)
左查詢
select c.Name as Customers from Customers c left join Orders o on o.CustomerId = c.Id where o.Id is null;
EXISTS
select c.Name as Customers from Customers c where not exists (select 1 from Orders o where o.CustomerId = c.Id);