【leetcode刷题之MySQL】

175. 组合两个表

select firstName,lastName,city, state from Person left join Address on Person.personId=Address.personId

 LEFT JOIN:保留左表内容,右表不存在的列使用 Null 代替

RIGHT JOIN:保留右表中连接字段的内容,左表不存在的列使用NULL代替

INNER JOIN:保留左右两张表都存在的字段内容,不存在空值

176. 第二高的薪水

select ifnull((select max(distinct salary)  from Employee where salary<(select max(salary) from Employee)) ,null) as 'SecondHighestSalary'

 这里用判断空值的函数(ifnull函数)来处理特殊情况。

ifnull(a,b)函数:如果value不是空,结果返回a;如果value是空,结果返回b

178. 分数排名

select score,dense_rank() over (order by score desc) as ranking from Scores

这里考虑采用窗口函数:

1)rank函数:这个例子中是5位,5位,5位,8位,也就是如果有并列名次的行,会占用下一名次的位置。比如正常排名是1,2,3,4,但是现在前3名是并列的名次,结果是:1,1,1,4。

2)dense_rank函数:这个例子中是5位,5位,5位,6位,也就是如果有并列名次的行,不占用下一名次的位置。比如正常排名是1,2,3,4,但是现在前3名是并列的名次,结果是:1,1,1,2。

3)row_number函数:这个例子中是5位,6位,7位,8位,也就是不考虑并列名次的情况。比如前3名是并列的名次,排名是正常的1,2,3,4。

180. 连续出现的数字

select distinct l1.num as ConsecutiveNums from logs l1,logs l2,logs l3
where l1.id=l2.id-1 and l2.id=l3.id-1 and l1.num=l2.num and l2.num=l3.num

181. 超过经理收入的员工

select e1.name as Employee from Employee e1,Employee e2  where e1.managerId=e2.id and e1.salary>e2.salary

182. 查找重复的电子邮箱

select email as Email from Person group by Email having count(Email)>1

183. 从不订购的客户

select name as Customers from Customers where id not in(select customerId from Orders)