CREATEFUNCTION getNthHighestSalary(N INT) RETURNSINT BEGIN set N := N-1; RETURN ( # Write your MySQL query statement below. select (selectdistinct salary from Employee orderby salary desc limit 1offset N) ); END
select a.score, ( # 拿a.score重新重新去检索一次表,得到count(distinct b.score)+1,得到自己的排名 selectcount(distinct b.score)+1from Scores b where a.score<b.score ) as `rank` from Scores a orderby a.score desc
但效率太慢。
高速的序号方法:
使用dense_rank() over(order by xxx) 可以得到序号,1 1 2 3 3 4,不会跳序号
其他序号方式:
row_number() over(order by xxx) 就是简单的12345这种,不考虑重复
rank() over(order by xxx) 如果重复了,1 1 3 4 4 6
1 2 3
select score, (dense_rank() over(orderby score desc) ) as `rank` from Scores
寻找3个连续出现的数字,如果id是连续的,则可以自联结,即自己和自己join, 构造where a.id = b.id-1 and b.id = c.id-1 这样的情况。非常好理解
1 2 3 4 5 6
selectdistinct a.num as ConsecutiveNums from logs a,logs b, logs c where a.id = b.id-1 and b.id = c.id-1 and a.num = b.num and b.num = c.num
善用自join联结解决一些表内成员互相比较的复杂问题。
1 2 3 4 5 6
# 查询收入超过他经理的员工名字。 select a.name as Employee from Employee a , Employee b where b.id = a.managerId and a.salary > b.salary
group分组后, 可以用having进行组内聚合情况的过滤, 剔除不想要的组
1 2 3 4 5
# 查找 Person 表中所有重复的电子邮箱。 select email from person groupby email having count(email) >1;
表a在 表b中不存在记录, 用left join + where xxx is null 来处理
1 2 3
select c.name as Customers from Customers c leftjoin Orders o on c.id = o.CustomerId where o.id isnull
in 的用法 where a in(1,2,3,4)
或者 where a in (select aaa from xxx)
in也支持二元组形式
where (a,b) in (select aaa,bbb from xxx)
每组最大值的人选的情况,可以用join + in(分组结果)的方法
1 2 3 4 5 6 7 8 9 10 11 12
# 查找每个部门中薪资最高的员工,先join,再用in获取符合组+最大值的行 select b.name as Department , a.name as Employee , a.salary as Salary from Employee a join Department b on a.departmentId = b.id and(a.departmentId, a.salary) in ( select departmentId, max(salary) from Employee group by departmentId )
# 找出每个部门获得前三高工资的所有员工 select b.name as Department , a.name as Employee , a.salary as Salary from Employee a join Department b on a.departmentId = b.id # 比自己这行记录salary大, 且在同一组内的数量小于3,则满足前3 and (selectcount(distinct e.salary) from Employee e where a.DepartmentId = e.DepartmentId and a.salary < e.salary ) <3