MySQL8中的关键字window
见字知意,与Java、python等编程语言中关键字如出一辙。MySQL中保留的关键字多达900多个,其中我们较为熟悉的有select、insert、update等等。window关键字一般与窗口函数配合使用。
下面看一个例子:
有如下表格,表名:order_tab。orderi_id:“订单编号”;product_id:“商品编号”;amount:“订单金额”;create_date:“订单创建日期”。
order_id | product_id | amount | create_date |
---|---|---|---|
1 | a | 200 | 2020-09-01 |
2 | a | 300 | 2020-09-03 |
3 | b | 200 | 2020-09-03 |
4 | a | 300 | 2020-09-02 |
5 | b | 300 | 2020-09-02 |
6 | b | 200 | 2020-09-01 |
select * from
(
select *,row_number() over w as row_num,
from order_tab
WINDOW w AS (partition by product_id order by amount desc)
)t ;
window关键字的作用就是为当前窗口起别名。在本语句中,将当前窗口命名为w。
该语句的含义为按照product_id进行分组,并在组内根据amount值进行降序排列。
此处row_number()为窗口函数,参见另一篇文章:MySQL8窗口函数的语法与示例详解
- 等价于以下语句
select * from
(
select *,row_number() over (partition by product_id order by amount desc) as row_num,
from order_tab
)t ;
- 结果如下:
order_id | product_id | amount | create_date | row_num |
---|---|---|---|---|
2 | a | 300 | 2020-09-03 | 1 |
4 | a | 300 | 2020-09-02 | 2 |
1 | a | 200 | 2020-09-01 | 3 |
5 | b | 300 | 2020-09-02 | 1 |
3 | b | 200 | 2020-09-03 | 2 |
6 | b | 200 | 2020-09-01 | 3 |