力扣(LeetCode)中、数据库模块题解
因为工作原因,对博客的更新也变少了
这里会持续更新这篇博客,来提升自己对sql语句的编写
如果有可以优化的地方,请多多指出
废话就不多说了,这里直接上sql语句
175.组合两个表
select p.FirstName,p.LastName,a.City,a.State from person p left join address a on p.personid=a.personid 分析: { 1、on条件是在生成临时表时使用的条件,它不管on中的条件是否为真,都会返回左边表中的记录。 2、where条件是在临时表生成好后,再对临时表进行过滤的条件。这时已经没有left join的含义(必须返回左边表的记录)了,条件不为真的就全部过滤掉。 }
176.第二高的薪水
select IFNULL((select distinct salary from Employee order by salary desc limit 1,1), null) as SecondHighestSalary
177.第N高的薪水
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT BEGIN SET N = N-1; RETURN ( # Write your MySQL query statement below. SELECT DISTINCT salary FROM employee order by salary desc limit N,1 ); END
178.分数排名
select a.score as score ,(select count(distinct b.score) from scores b where a.score >= b.score) as 'rank'
from scores a order by a.score desc;
(优化)select Score, dense_rank() over (order by Score desc) as `Rank` from Scores;
分析:
{
rank() over:查出指定条件后的进行排名。特点是,加入是对学生排名,使用这个函数,成绩相同的两名是并列,下一位同学空出所占的名次。
dense_rank() over:与ran() over的区别是,两名学生的成绩并列以后,下一位同学并不空出所占的名次。
row_number() over这个函数不需要考虑是否并列,哪怕根据条件查询出来的数值相同也会进行连续排名。
}
180.连续出现的数字
select distinct a.Num as ConsecutiveNums from Logs as a,Logs as b,Logs as c where a.Num=b.Num and b.Num=c.Num and a.id=b.id-1 and b.id=c.id-1;
(优化) select distinct(l.Num) ConsecutiveNums from Logs l inner join Logs l2 on l.Num = l2.Num and l.id = l2.id+1 inner join Logs l3 on l.Num = l3.Num and l.id = l3.id+2
181.超过经理收入的员工
select a.name as Employee from Employee a LEFT JOIN Employee b ON a.ManagerId = b.Id where a.Salary > b.Salary
浙公网安备 33010602011771号