最近发现leetcode还有mysql的题目,于是尝试做了几道
](https://1000bd.com/contentImg/2022/07/02/080238729.png)
编写一个SQL查询来报告 Person 表中每个人的姓、名、城市和州。如果 personId 的地址不在 Address 表中,则报告为空 null 。
以 任意顺序 返回结果表。
查询结果格式如下所示。

首先组合表,可以想到使用连接,于是使用了inner join,但运行时发现还有一种null的情况,于是改用左外连接,这样就会填充null
select p.firstName,p.lastName,a.city,a.state
from Person p right join Address a
on p.personId=a.personId;

. 
编写一个 SQL 查询,获取并返回 Employee 表中第二高的薪水 。如果不存在第二高的薪水,查询应该返回 null 。
查询结果如下例所示。


这里思路开始是取排序的第二个
select ifnull((select salary from Employee order by Employee.salary desc limit 1,1),null) as SecondHighestSalary;
但发现有重复,那么就去重
select ifnull((select distinct salary from Employee order by Employee.salary desc limit 1,1),null) as SecondHighestSalary;
这样可以了
于是也可以使用
select max(Salary) SecondHighestSalary
from Employee
where Salary < (select max(Salary) from Employee)

编写一个SQL查询来报告 Employee 表中第 n 高的工资。如果没有第 n 个最高工资,查询应该报告为 null 。
查询结果格式如下所示。


思路和上个题一样
select distinct salary from Employee order by Employee.salary desc limit n-1,1
但发现这个是function,那么n-1是不行的
于是set n = n-1
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 Employee.salary desc limit n,1
);
END

来源:力扣(LeetCode)
链接:https://leetcode.cn/problems/combine-two-tables
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。