数据库每日两题之一
题目如下
思路一:全局查询
首先可以想到先order by 排序,再用limit和offset,语法如下:
limit y : 读取 y 条数据
limit x, y : 跳过 x 条数据,读取 y 条数据
limit y offset x : 跳过 x 条数据,读取 y 条数据
也就是跳过N-1条数据,读取一条数据
还有个细节就是limit后面必须是正整数,不能是表达式,所以N=N-1
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET N=N-1;
RETURN (
# Write your MySQL query statement below.
select Salary
from Employee
order by Salary desc
limit N,1
);
END
提交时出错
观察可知题目要求对同值薪水应取相同排名、
可以用group by 薪水 使相同薪水在同一组,一组一个排名
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
SET N=N-1;
RETURN (
# Write your MySQL query statement below.
select Salary
from Employee
group by Salary
order by Salary desc
limit N,1
);
END
思路二 :自连接
使用别名表1,表2区分
表1的salary1连接表2中大于salary1的salary2,用group by salary1进行分组
使用having count()对分组进行筛选,选出有N-1个元组的组别即为排名第N,同值情况用distinct去重
考虑边界值情况N=1,此时没有比它大的,N-1=0,但仍需保留结果,考虑用left join保留。或者是将条件放宽到大于等于,此时筛选条件应为N
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
# Write your MySQL query statement below.
select distinct e1.Salary
from Employee e1 join Employee e2 on e1.Salary<=e2.Salary
group by e1.Salary
having count(distinct e2.Salary)=N
);
END
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
RETURN (
# Write your MySQL query statement below.
select distinct e1.Salary
from Employee e1 left join Employee e2 on e1.Salary<e2.Salary
group by e1.Salary
having count(distinct e2.Salary)=N-1
);
END
使用left join时出现问题:
count计数会忽略空值,为什么会出现这个结果?