数据库入门day6&day7 高难度力扣题解通关数据库

leetcode数据库经典题题解

181. 超过经理收入的员工 - 力扣(LeetCode)

  • 1、通过自连接,先找到员工的经理。
  • 2、找到员工对应的经理后,再对比两者工资。
  • 3、选择满足条件的员工名字返回即可。
select a.name as Employee from Employee a,Employee b where a.managerId = b.id and a.salary > b.salary;

176. 第二高的薪水 - 力扣(LeetCode)

  • 1、要想获取第二高,需要排序,使用 order by desc
  • 2、去重,如果有多个相同的数据,使用关键字 distinct 去重
  • 3、判断临界输出,如果不存在第二高的薪水,查询应返回 null,使用 ifNull(查询,null)方法 ifnull 如果返回值空的化返回一个不为空的值 此题返回一个null
  • 4、起别名,使用关键字 as …
  • 5、因为去了重,又按顺序排序,使用 limit()方法,查询第二大的数据,即第二高的薪水,即 limit(1,1) (因为默认从0开始,所以第一个1是查询第二大的数,第二个1是表示往后显示多少条数据,这里只需要一条)
select ifnull ((select distinct salary  from Employee order by salary desc limit 1 offset 1) ,null)as SecondHighestSalary;

183. 从不订购的客户 - 力扣(LeetCode)

左外连接:通过左连接当右表中空即是所求

select Name as Customers from Customers left join Orders on Customers.Id = Orders.CustomerId where CustomerId is null;

184. 部门工资最高的员工 - 力扣(LeetCode)

内部嵌套查询:先找出max(salary)然后通过departmentId,max(salary)的值来查询外部多表联合之后所需要的信息

select 
d.name as Department,e.name as Employee,e.Salary 
from 
Employee e inner join Department d 
on 
e.departmentId = d.id 
where 
(e.DepartmentId,e.Salary) in (select departmentId,max(Salary) from Employee group by departmentId);

196. 删除重复的电子邮箱 - 力扣(LeetCode)

注意:在MYSQL中,不能先Select一个表的记录,再按此条件Update和Delete同一个表的记录,否则会出错:You can’t specify target table ‘xxx’ for update in FROM clause.

DELETE 
from Person
where id not in(select id from Person group by email);

解决方法:使用嵌套Select——将Select得到的查询结果作为中间表,再Select一遍中间表作为结果集,即可规避错误。

DELETE 
from Person
where id not in(select id from (select min(id) as id from Person group by email) t);
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值