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'
相关推荐
数据库知识分享者小北4 小时前
云栖重磅|瑶池数据库:从云原生数据底座向“AI就绪”的多模态数据底座演进
数据库·人工智能·云原生
_Johnny_4 小时前
Redis 升级操作指南:单机与主从模式
数据库·redis·缓存
源力祁老师4 小时前
ODOO数据文件(XML、CSV、SQL)是如何转换并加载到 Odoo 数据库
xml·数据库·sql
提笔了无痕4 小时前
什么是Redis的缓存问题,以及如何解决
数据库·redis·后端·缓存·mybatis
苏小瀚5 小时前
[MySQL] 索引
数据库·mysql
lang201509285 小时前
Spring Boot SQL数据库全攻略
数据库·spring boot·sql
EndingCoder5 小时前
MongoDB基础与Mongoose ODM
服务器·javascript·数据库·mongodb·中间件·node.js
赋能大师兄6 小时前
SQLITE数据库完成数据增删改查
数据库·sqlite
一个天蝎座 白勺 程序猿6 小时前
深度解析:通过ADO.NET驱动Kdbndp高效连接与操作Kingbase数据库
数据库·.net·wpf·kingbase·金仓数据库
AI科技星7 小时前
垂直原理:宇宙的沉默法则与万物运动的终极源头
android·服务器·数据结构·数据库·人工智能