书接上回
7、多表查询的精髓是: 根据关联条件把多张表变成一张表, 然后进行"单表"查询.
1) 交叉查询
格式: select * from 表A, 表B;
select * from hero, kongfu; -- 会产生大量的 脏数据, 实际开发不用.
2) 连接查询
场景1: 内连接, 查询结果: 表的交集
格式1: 显式内连接. select * from A inner join B on 关联条件 where ...;
select * from hero h inner join kongfu kf on h.kongfu_id = kf.kid;
select * from hero h join kongfu kf on h.kongfu_id = kf.kid; # inner 可以省略不写
场景2: 外连接.
格式1: 左外连接. select * from A left outer join B on 关联条件 where ...;
结果: 左表全集 + 交集
select * from hero h left outer join kongfu kf on h.kongfu_id = kf.kid;
select * from hero h left join kongfu kf on h.kongfu_id = kf.kid; # outer可以省略
格式2: 右外连接. 结果: 右表全集 + 交集
select * from hero h right join kongfu kf on h.kongfu_id = kf.kid; # outer可以省略
三、窗口函数
1、概述:
入门阶段的窗口函数主要是: row_number(), rank(), dense_rank(), 主要是用来做: 排名的.
简单来说,窗口函数 = 给表 新增1列, 至于新增的一列是什么内容, 取决于你的窗口函数是怎么写的.
2、格式:
开窗函数 over(partition by 分组字段 order by 排序字段 asc | desc)
格式解释:
开窗口函数: 这里指的是 row_number(), rank(), dense_rank()等
over(): 固定格式, 里边写的是: 分组, 排序的相关操作.
partition by: 类似于group by, 做分组的.
order by: (局部)排序的, 即: 组内排序.
细节:
1. row_number(), rank(), dense_rank()主要区别就是 遇到相同数据了, 如何处理, 具体如下:
例如: 数据为, 100, 90, 90, 80
则:
row_number(): 1, 2, 3, 4
rank(): 1, 2, 2, 4
dense_rank(): 1, 2, 2, 3
( 窗口函数是MySQL8.X的新特性)
3、应用案例
对employee表中按照deptid进行分组,并对每一组的员工按照薪资进行排名:分组排名.
select
*,
row_number() over(partition by deptid order by salary desc) as rn,
rank() over(partition by deptid order by salary desc) as rk,
dense_rank() over(partition by deptid order by salary desc) as dr
from employee;