假设一个网站有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/

本文介绍了一种使用SQL语句来查询从未下过订单的客户的方法。通过对比Customers和Orders两个表,利用NOT IN操作符筛选出那些在Orders表中没有对应记录的客户。
1629

被折叠的 条评论
为什么被折叠?



