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 | +-----------+
题目是想将Customers中某一类name显示出来,这个条件通过Orders判断。
可以通过left join将Customers与Orders连接起来,然后筛选出符合条件的。
以例题为例:
Customers left join Orders的结果:
条件是:没有订单的顾客的名字,表示为CustomerId is NULL;
select Customers.Name as Customers
from Customers
left join Orders
on Customers.Id=Orders.CustomerId
where Orders.CustomerId is NULL;