项目需求:

需要获取部门表的递归数据。
示例 sys_dept表 数据:

WITH RECURSIVE ... AS - 图1

利用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 ... AS - 图2

- 查找子级信息
-- 找子级
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 

查询结果:

WITH RECURSIVE ... AS - 图3

附:表结构和数据

-- 建表
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');