sql递归查询
项目需求:
需要获取部门表的递归数据。
示例表数据:
利用sql语法中的 recursive关键字
递归查询:
关键字-recursive 递归层级-mu_level
数据库版本:MySQL 8.0.12 PostgreSQL 10.17
- 查找父级信息
-- 找父级with recursive role_table (dept_code,dept_name,dept_pcode,mu_level)as ( select dt.dept_code,dt.dept_name,dt.dept_pcode,0 as mu_level from sys_dept dt where dt.dept_code = '100101' union all //已知的是子集,所以我们通过role_table的dept_pcode 匹配 sys_dept的dept_code select dt.dept_code,dt.dept_name,dt.dept_pcode,mu_level+1 from sys_dept dt inner join role_table rt on rt.dept_pcode = dt.dept_code)select rt.* from role_table rt
查询结果:
- 查找子级信息
-- 找子级with recursive role_table (dept_code,dept_name,dept_pcode,mu_level)as ( select dt.dept_code,dt.dept_name,dt.dept_pcode,0 as mu_level from sys_dept dt where dt.dept_code = '1001' union all select dt.dept_code,dt.dept_name,dt.dept_pcode,mu_level+1 from sys_dept dt inner join role_table rt on rt.dept_code = dt.dept_pcode)select rt.* from role_table rt
查询结果:
附:表结构和数据
-- 建表CREATE TABLE `sys_dept` ( `dept_id` int(11) NOT NULL AUTO_INCREMENT COMMENT '部门id', `dept_code` varchar(50) NOT NULL COMMENT '部门编码', `dept_name` varchar(10) NOT NULL COMMENT '部门名称', `dept_pcode` varchar(50) CHARACTER SET utf8 COLLATE utf8_general_ci DEFAULT NULL COMMENT '上级部门代码', PRIMARY KEY (`dept_id`)) ENGINE=InnoDB AUTO_INCREMENT=8 DEFAULT CHARSET=utf8;-- 数据INSERT INTO `clothes`.`sys_dept`(`dept_id`, `dept_code`, `dept_name`, `dept_pcode`) VALUES (1, '10', '龙睿集团', NULL);INSERT INTO `clothes`.`sys_dept`(`dept_id`, `dept_code`, `dept_name`, `dept_pcode`) VALUES (2, '1001', '龙睿科技', '10');INSERT INTO `clothes`.`sys_dept`(`dept_id`, `dept_code`, `dept_name`, `dept_pcode`) VALUES (3, '100101', '研发中心', '1001');INSERT INTO `clothes`.`sys_dept`(`dept_id`, `dept_code`, `dept_name`, `dept_pcode`) VALUES (4, '10010101', 'Java组', '100101');INSERT INTO `clothes`.`sys_dept`(`dept_id`, `dept_code`, `dept_name`, `dept_pcode`) VALUES (5, '10010102', '产品UI', '100101');INSERT INTO `clothes`.`sys_dept`(`dept_id`, `dept_code`, `dept_name`, `dept_pcode`) VALUES (6, '10010103', 'H5大前端', '100101');INSERT INTO `clothes`.`sys_dept`(`dept_id`, `dept_code`, `dept_name`, `dept_pcode`) VALUES (7, '100102', '行政人事部', '1001');
参考文章:
https://www.jb51.net/article/202247.htm
https://www.bianchengquan.com/article/340193.html
Thanks♪(・ω・)ノ
作者:龙小胖
来源链接:https://blog.csdn.net/weixin_43706875/article/details/124801027
版权声明:
1、JavaClub(https://www.javaclub.cn)以学习交流为目的,由作者投稿、网友推荐和小编整理收藏优秀的IT技术及相关内容,包括但不限于文字、图片、音频、视频、软件、程序等,其均来自互联网,本站不享有版权,版权归原作者所有。
2、本站提供的内容仅用于个人学习、研究或欣赏,以及其他非商业性或非盈利性用途,但同时应遵守著作权法及其他相关法律的规定,不得侵犯相关权利人及本网站的合法权利。
3、本网站内容原作者如不愿意在本网站刊登内容,请及时通知本站(javaclubcn@163.com),我们将第一时间核实后及时予以删除。