一、目标及效果预览
- 实现查询数据生成行序号
- 实现分组查询数据生成行序号
二、开发环境
三、代码实现
-- 创建t_book
create table t_book(
id int primary key not null auto_increment comment '主键' ,
book_name varchar(50) not null comment '书名' ,
book_cate varchar(50) not null comment '分类'
)ENGINE = InnoDB CHARACTER SET = utf8mb4 COLLATE = utf8mb4_0900_ai_ci COMMENT = '书库';
-- 插入数据
insert into t_book (book_name,book_cate) values ('java编程思想','java'),('effective java','java'),('python高性能编程','python'),('python编程','python');
- 行序号: 核心思想借助mysql中的用户变量@,也是会话变量。(系统变量@@)
select
(@rowNum := @rowNum + 1) as rowNum
,b.id
,b.book_name
,b.book_cate
from t_book as b
,(SELECT @rowNum:=0) as rn ;
- 分组行序号: 核心思想是排序后,借助另一个变量记录分组
select
(@rowNum := case when @pre_parent_code=b.book_cate then @rowNum + 1 else 1 end )as rowNum
,b.id
,b.book_name
,b.book_cate
, (@pre_parent_code:= b.book_cate ) as ppc
from t_book as b
,(SELECT @rowNum:=0, @pre_parent_code:='') as rn
order by b.book_cate
四、写在最后
此思路仅供参考,如有错误,感谢请指正讨论。
|