LeetCode MySQL刷题记录(随时更新)
175.组合两个表
题目描述:
表1: Person
+-------------+---------+ | 列名 | 类型 | +-------------+---------+ | PersonId | int | | FirstName | varchar | | LastName | varchar | +-------------+---------+ PersonId 是上表主键
表2: Address
+-------------+---------+ | 列名 | 类型 | +-------------+---------+ | AddressId | int | | PersonId | int | | City | varchar | | State | varchar | +-------------+---------+ AddressId 是上表主键
编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:
FirstName, LastName, City, State
解题思路:
很简单,考察的是* left join * on
select p.FirstName,p.LastName,a.City,a.State from Person p left join Address a on p.PersonId=a.PersonId;
176.第2高的薪水
题目描述:
编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
+---------------------+ | SecondHighestSalary | +---------------------+ | 200 | +---------------------+
解题思路:
1.排序与分页的组合,order by 与limit start,offset 2.若为空,则返回null,使用IFNULL函数或者嵌套查询 3.不同Id薪水可能存在重复情况,使用distinct关键字进行去重
IFNULL(expression_1,expression_2);
如果expression_1不为NULL,则IFNULL函数返回expression_1; 否则返回expression_2的结果。
解法1(嵌套查询):
select (select distinct Salary from Employee order by Salary desc limit 1,1) as SecondHighestSalary
解法2(IFNULL函数查询):
select ifnull((select distinct Salary from Employee order by Salary desc limit 1,1), null) as SecondHighestSalary;
177.第N高的薪水
题目描述:
编写一个 SQL 查询,获取 Employee 表中第 n 高的薪水(Salary)。
+----+--------+ | Id | Salary | +----+--------+ | 1 | 100 | | 2 | 200 | | 3 | 300 | +----+--------+
例如上述 Employee 表,n = 2 时,应返回第二高的薪水 200。如果不存在第 n 高的薪水,那么查询应返回 null。
+------------------------+ | getNthHighestSalary(2) | +------------------------+ | 200 | +------------------------+
解题思路:
1.题目中给出了创建方法的标本 2.注意RETURN中不能使用加减法?还没找到答案,需要在RETURN之前加入SET N=N-1;
解法:
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT BEGIN set n=N-1; RETURN ( # Write your MySQL query statement below. select ifnull( (select distinct Salary from Employee order by Salary desc limit n,1) , null) as getNthHighestSalary ); END
下一篇:
第十三周总结——认清自己