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 | +-----------+
想到两种方法:left join,not in。
not in:
select Customers.Name
from Customers
where Customers.Id not in (select distinct CustomerId from Orders);
left join:
SELECT Name
FROM Customers c LEFTJOIN Orders o ON c.Id = o.CustomerId
WHERE o.Id ISNULL;
在网上还看见一种方法:not exists:
SELECT Name FROM Customers c
WHERENOTEXISTS (SELECT CustomerId FROM Orders o WHERE o.CustomerId = c.id);