https://leetcode-cn.com/problems/combine-two-tables/
Create table Person (PersonId int, FirstName varchar(255), LastName varchar(255))
Create table Address (AddressId int, PersonId int, City varchar(255), State varchar(255))
Truncate table Person
insert into Person (PersonId, LastName, FirstName) values ('1', 'Wang', 'Allen')
Truncate table Address
insert into Address (AddressId, PersonId, City, State) values ('1', '2', 'New York City', 'New York')
编写一个 SQL 查询,满足条件:无论 person 是否有地址信息,都需要基于上述两表提供 person 的以下信息:
FirstName, LastName, City, State
只要person表有内容,则有结果→左外连接
SELECT x1.FirstName, x1.LastName, X2.City, x2.State
FROM Person x1 LEFT JOIN Address x2 ON x1.PersonId = x2.PersonId
https://leetcode-cn.com/problems/second-highest-salary/
Create table If Not Exists Employee (Id int, Salary int)
Truncate table Employee
insert into Employee (Id, Salary) values ('1', '100')
insert into Employee (Id, Salary) values ('2', '200')
insert into Employee (Id, Salary) values ('3', '300')
例如上述 Employee 表,SQL查询应该返回 200 作为第二高的薪水。如果不存在第二高的薪水,那么查询应返回 null。
order by排序
SELECT Salary AS SecondHighestSalary
FROM Employee
ORDER BY Salary DESC LIMIT 1,1
结果是错误的,错在不满足如果不存在第二高的薪水,那么查询应返回 null。
正确答案
(1)创建临时表
SELECT(SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC LIMIT 1,1) AS SecondHighestSalary;
注意DISTINCT,如果没有的话会返回重复值(比如最高是100,有两个100,不加DISTINCT就会返回100)
(2)IFNULL
SELECT IFNULL((SELECT DISTINCT Salary
FROM Employee
ORDER BY Salary DESC LIMIT 1,1),NULL) AS SecondHighestSalary;
(3)子查询排除掉最大的
SELECT MAX(Salary) AS SecondHighestSalary
FROM Employee
WHERE Salary < (SELECT MAX(Salary) FROM Employee);
这种方法可以找出第二高的,但如果要的是第三高、第四高……需要写很多个子查询。