Leetcode SQL[175][176][181]
[175] Combine two tables
表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
思路
因为要求为:无论person有无地址,都要输出。所以不能使用内连接而应该是外连接,并令Person表为主表
代码
法一
select p.firstname,p.lastname,a.city,a.state
from person as p left outer join address as a -- left out join
on p.personid = a.personid;
[176] Second highest salary
题目
编写一个 SQL 查询,获取 Employee 表中第二高的薪水(Salary) 。
±—±-------+
| Id | Salary |
±—±-------+
| 1 | 100 |
| 2 | 200 |
| 3 | 300 |
±—±-------+
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
±--------------------+
| SecondHighestSalary |
±--------------------+
| 200 |
±--------------------+
思路
法一:子查询-找出最大的,然后找到除此之外最大的
法二:学习了limit offset的用法
代码
Method 1
select max(distinct salary) as SecondHighestSalary
from Employee
where salary not in (select max(salary) from employee);
Method 2
# Write your MySQL query statement below
select ifnull((select distinct salary from employee
order by salary desc
limit 1,1),null) as secondhighestsalary;
[181] Employees earning more than their managers
题目
Employee 表包含所有员工,他们的经理也属于员工。每个员工都有一个 Id,此外还有一列对应员工的经理的 Id。
±—±------±-------±----------+
| Id | Name | Salary | ManagerId |
±—±------±-------±----------+
| 1 | Joe | 70000 | 3 |
| 2 | Henry | 80000 | 4 |
| 3 | Sam | 60000 | NULL |
| 4 | Max | 90000 | NULL |
±—±------±-------±----------+
给定 Employee 表,编写一个 SQL 查询,该查询可以获取收入超过他们经理的员工的姓名。在上面的表格中,Joe 是唯一一个收入超过他的经理的员工。
±---------+
| Employee |
±---------+
| Joe |
±---------+
思路
关联子查询
员工为一张表,其salary要比他的manager高(子查询,用到另一张表来指定salary)
代码
select name as employee
from employee as p1
where p1.salary > (select p2.salary from employee as p2
where p2.id = p1.managerid);
收获
刚开始学习MySQL不久,主要在自己系统性地看书,希望在leetcode上多练练好准备面试!