机器学习与数据挖掘数据/数据库

LeetCode-SQL-two

2020-02-07  本文已影响0人  皮皮大

LeetCode-SQL-two

本文中主要是介绍LeetCode中关于SQL的练习题,从易到难,循序渐进。文中会介绍题目和尽可能多的解答方案

关于SQL连接的问题解决,牢记下图

image

182-查找重复的电子邮箱

题目

编写一个 SQL 查询,查找 Person 表中所有重复的电子邮箱。

image

输出结果为:

image

答案

子句顺序:where>group by>having>order by

-- 自己的答案
select distinct(Email)   -- 去重
from Person a,
     Person b
 where a.Email=b.Email   -- 过滤条件
 and a.id != b.id;

最好的方法

select Email   
from Person 
group by Email  -- 分组
having count(Email) > 1;  -- 过滤
select distinct(p1.Email)
from Person a
join Person b on a.Email=b.Email
and a.id != b.id;   -- 和自己的类似,将where条件换成了join连接

使用临时表解决

select Email 
from (
  select Email, count(Email) as num
  from Person
  group by Email
) as statistic   -- 建立临时表,必须要有
where num > 1;

183-从不订购的客户

题目

某网站包含两个表,Customers 表和 Orders 表。编写一个 SQL 查询,找出所有从不订购任何东西的客户。

image

输出结果为

image

答案

-- 自己答案
select Name as 'Customers'
from Customers
where Customers.Id not in 
(select CustomerId
from Orders
join Customers on Orders.CustomerId=Customers.Id);
-- 官方答案
select customers.name as 'Customers'
from customers 
where customers.id not in (
      select customerid from orders
)
-- 根据SQL连接来解决:查找不在某个表中的数据,在a中,但是不在b中

select a.Name as Customers
from Customers a 
left join Orders as b
on a.Id=b.CustomerId
where b.CustomerId is null;   -- b中是空的;不能用 =null
image
上一篇 下一篇

猜你喜欢

热点阅读