SQL Server 每日一题--解析只逛不买

时间:2022-07-24
本文章向大家介绍SQL Server 每日一题--解析只逛不买,主要内容包括其使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

这个题目经常用到的解决方法有两种,第一种方法是大多数人首先想到的利用 not in 或者 not exists,第二种方法是利用 left join 。下面我们来分别看看这两种方法。

零、解析

1.not in / not exists

  • not in 首先我们查询订单表中 CustomersId ,并去重。这些 Id 都是有购买记录的会员的Id。
select distinct CustomerId from orders

然后将查询出来的 CustomerId 作为过滤条件,查询 Customers 表并过滤掉查询出来的 CustomerId,这样就查询出没有买过一件东西的会员了。

select Name from Customers where Id not in (select CustomerId from orders)
  • not exists 与 not in 同理
SELECT c.Name
FROM Customers AS c
WHERE NOT EXISTS
(
    SELECT CustomerId FROM Orders WHERE c.Id = CustomerId
);

2.left join 利用 left join 去除 null 值的功能也可以的,这种方法相比上面的方法要相对简单快捷。

SELECT c.Name
FROM Customers AS c
    LEFT JOIN Orders AS o
        ON c.Id = o.CustomerId
WHERE o.Id IS NULL;