問題:web
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.spa
Table: Customers
.code
+----+-------+ | Id | Name | +----+-------+ | 1 | Joe | | 2 | Henry | | 3 | Sam | | 4 | Max | +----+-------+
Table: Orders
.it
+----+------------+ | Id | CustomerId | +----+------------+ | 1 | 3 | | 2 | 1 | +----+------------+
Using the above tables as example, return the following:table
+-----------+ | Customers | +-----------+ | Henry | | Max | +-----------+
① 使用NOT IN,找沒有在Orders表中出現的顧客Id。769 mstab
SELECT Name AS Customers FROM Customers
WHERE Id NOT IN (SELECT CustomerId FROM Orders);query
② 使用NOT EXISTS。795 msco
SELECT Name AS Customers FROM Customers c
WHERE NOT EXISTS (SELECT * FROM Orders o WHERE o.CustomerId = c.Id);return
SELECT Name AS Customers FROM Customers c
WHERE NOT EXISTS(SELECT CustomerId FROM Orders o WHERE c.Id = o.CustomerId);ab
③ 用左交來聯合兩個表,只要找出右邊的CustomerId爲Null的顧客就是沒有下單的。795ms
SELECT Name AS Customers
FROM Customers c LEFT JOIN Orders o ON c.Id = o.CustomerId
WHERE o.CustomerId IS NULL;