mysql 8递归查询

带有排序和层级

bash 复制代码
 with recursive cte as
        (
        select *, cast(order_num as char(1000)) as sort_path, 1 as level from com_office_project_wbs where id = '1942822902508290048'
        union all
        select c.*, concat(cte.sort_path, '-', c.order_num), cte.level + 1  from com_office_project_wbs c, cte where c.parent_id = cte.id
        )
        select t.sort_path,t.level, t.* from cte t 
ORDER BY sort_path

向上查

bash 复制代码
with recursive cte as
(
select * from com_office_project_wbs where id = '1942824126712381440'
union all
select c.* from com_office_project_wbs c, cte where c.id = cte.parent_id
)
select * from cte t 

向下查询

bash 复制代码
	 with recursive cte as
(
select * from com_office_project_wbs where id = '1942822902508290048'
union all
select c.* from com_office_project_wbs c, cte where c.parent_id = cte.id
)
select * from cte t 

查询孩子节点数量

bash 复制代码
with recursive cte as
           (
               select * from com_office_project_wbs where id = '1942822902508290048'
               union all
               select c.* from com_office_project_wbs c, cte where c.parent_id = cte.id
           )
    select IFNULL(count(1),0) cn from cte where id != '1942822902508290048'
相关推荐
zzhongcy24 分钟前
Valkey vs Redis详解
数据库·redis·缓存
技术小泽25 分钟前
Redis-底层数据结构篇
数据结构·数据库·redis·后端·性能优化
TsengOnce34 分钟前
MySQL 性能调优与 SQL 优化的核心利器
android·sql·mysql
longze_742 分钟前
数据库事务的 ACID 四大性质
数据库·oracle
gihigo199844 分钟前
MySQL中binlog、redolog与undolog的不同之处解析
数据库·mysql·oracle
GottdesKrieges1 小时前
obdumper和obloader迁移OceanBase业务库(二):报错与调优
数据库·oceanbase
Pure03191 小时前
Spring 循环依赖问题
java·数据库·spring
budingxiaomoli1 小时前
MYSQL表的增删改查
数据库·sql·mysql
skywalk81632 小时前
mayfly-go:web 版 linux、数据库等管理平台
linux·运维·数据库
独行soc2 小时前
2025年渗透测试面试题总结-42(题目+回答)
android·数据库·安全·adb·面试·渗透测试·sqlite