183. Customers Who Never Order (LeetCode, SQL)

SQL查询未下单客户
本文介绍如何使用SQL查询找出从未下单的客户。通过两种方法实现:一是利用NOT IN子句直接筛选;二是采用LEFT JOIN左连接配合条件过滤,确保结果准确无误。

183. Customers Who Never Order

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.

IdName
1Joe
2Henry
3Sam
4Max

Table: Orders.

IdCustomerId
13
21

Using the above tables as example, return the following:

Customers
Henry
Max

解法1:

NOT IN

SELECT Name AS Customers 
From Customers 
WHERE Id NOT IN (SELECT CustomerId FROM Orders)

解法二:

LEFT JOIN

  • INNER JOIN(内连接,或等值连接):获取两个表中字段匹配关系的记录。
  • LEFT JOIN(左连接):获取左表所有记录,即使右表没有对应匹配的记录。
  • RIGHT JOIN(右连接): 与 LEFT JOIN 相反,用于获取右表所有记录,即使左表没有对应匹配的记录。
SELECT Name AS Customers
FROM Customers c  left join Orders o on c.Id=o.CustomerId
WHERE o.CustomerId IS NULL;
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值