SQL 是作为开发工程师、数据工程师必须要深入掌握的一项技能。我也一直在提升这部分的能力,从入门到精通。除了阅读一些 SQL 经典书籍,刷题也是一个不错的选择。于是,我将做过的题目与解法,汇总到这里,和大家一起学习。
SQL 练习题系列和「体验碎片」系列一样,会不定期进行更新。
问题:根据 Customers 表和 Orders 表,编写一个 SQL 查询,找出所有从不订购任何东西的客户。
预期结果
解法1:子查询
1.在 Orders 表中找出所有购买的用户,并对用户去重。2.从不订购的用户就是 Customers 的用户不在 Orders 中,使用 not in 即可。
select c.Name as Customersfrom Customers as cwhere c.Id not in (select CustomerId from Orders group by CustomerId)
解法2:左连接
1.找出所有从不订购任何东西的客户,意思为将 Customers 作为主表,左连接 Orders。2.使用 left join 连接时,如果是没有订购的用户,订单表 ID 字段为 null 值。3.使用 where 条件筛选出 CustomerI 为空的用户,就找到了从不订购任何东西的客户。
select c.Name as Customersfrom Customers as c left join Orders as o on o.CustomerId = c.Idwhere o.CustomerId is null
![9754ff19de08e7ca51d3ea8897bac799.png](https://i-blog.csdnimg.cn/blog_migrate/c7c8652971e234f793c287f1f6ab4256.png)