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
177. 第N高的薪水
CREATE FUNCTION getNthHighestSalary(N INT) RETURNS INT
BEGIN
set N=N-1;
RETURN (
select salary from employee group by salary order by salary desc limit N,1
);
END
这段代码定义了一个名为
getNthHighestSalary
的函数,该函数接受一个整数参数N
,并返回一个整数值。
BEGIN
: 标志着函数体的开始。
END
: 标志着函数体的结束LIMIT N, 1的含义:比如如果使用
LIMIT 3, 2
,这意味着从第 4 行(索引为 3)开始,选择 2 行数据。所以它会返回第 4 和第 5 行数据。
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)
184. 部门工资最高的员工
select Department.name as Department,Employee.name as Employee,Salary from Employee join Department on Department.id=Employee.departmentId where (Employee.DepartmentId,Salary) in (select Departmentid,MAX(Salary) from Employee group by Departmentid)
185. 部门工资前三高的所有员工
select Department.name as Department,e1.name as Employee,e1.Salary as Salary from Employee as e1,Department
where e1.DepartmentId=Department.id and
3>(select count(distinct e2.salary) from Employee as e2
where e1.salary