题目
某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。
Customers
表:
+----+-------+
| Id | Name |
+----+-------+
| 1 | Joe |
| 2 | Henry |
| 3 | Sam |
| 4 | Max |
+----+-------+
Orders
表:
+----+------------+
| Id | CustomerId |
+----+------------+
| 1 | 3 |
| 2 | 1 |
+----+------------+
例如给定上述表格,你的查询应返回:
+-----------+
| Customers |
+-----------+
| Henry |
| Max |
+-----------+
题解
select name as Customers from customers
left join orders on customers.id = orders.customerid
where orders.customerid is null;
官方题解
使用子查询和 NOT IN 子句
订购过的客户名单
select customerid from orders;
然后,我们可以使用 NOT IN 查询不在此列表中的客户。
select customers.name as 'Customers'
from customers
where customers.id not in
(
select customerid from orders
);
not in
MySQL 中的 IN 运算符用来判断表达式的值是否位于给出的列表中;如果是,返回值为 1,否则返回值为 0。
NOT IN 的作用和 IN 恰好相反,NOT IN 用来判断表达式的值是否不存在于给出的列表中;如果不是,返回值为 1,否则返回值为 0。
版权声明:本文为LLcwh原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。