Mysql实现"从不订购的客户"的一种方法

假设一个网站有Customers和Orders两个表。写SQL语句查询所有没有下过订单的客户

Table: Customers.

+----+-------+
| Id | Name  |
+----+-------+
| 1  | Joe   |
| 2  | Henry |
| 3  | Sam   |
| 4  | Max   |
+----+-------+

Table: Orders.

+----+------------+
| Id | CustomerId |
+----+------------+
| 1  | 3          |
| 2  | 1          |
+----+------------+

上两表,返回结果为

+-----------+
| Customers |
+-----------+
| Henry     |
| Max       |
+-----------+

1:先查询下过订单的客户,然后用NOT IN查询没下过订单的客户(因为Name可能存在重名,所以用Id来做判断)

SELECT A.Name AS Customers
FROM  Customers AS A
WHERE A.Id NOT IN (SELECT C.Id 
                   FROM Customers AS C, Orders AS O
                   WHERE C.Id = O.CustomerId)

直接用NOT IN即可(参考他人)

select c.Name as Customers
from customers c
where c.id not in (select CustomerId from Orders)

算法题来自:https://leetcode-cn.com/problems/customers-who-never-order/description/

猜你喜欢

转载自blog.csdn.net/qiubingcsdn/article/details/82695080