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'
相关推荐
字节拾光录8 小时前
手机号存储避坑指南:从20亿级数据库实践看,为什么VARCHAR才是终极答案
java·数据库·oracle
q***465212 小时前
Win10下安装 Redis
数据库·redis·缓存
p***924814 小时前
深入理解与实战SQL IFNULL()函数
数据库·sql·oracle
q***816416 小时前
MySQL:数据查询-limit
数据库·mysql
p***924816 小时前
DBeaver连接本地MySQL、创建数据库表的基础操作
数据库·mysql
JIngJaneIL17 小时前
社区互助|社区交易|基于springboot+vue的社区互助交易系统(源码+数据库+文档)
java·数据库·vue.js·spring boot·论文·毕设·社区互助
晚风吹人醒.17 小时前
缓存中间件Redis安装及功能演示、企业案例
linux·数据库·redis·ubuntu·缓存·中间件
Y***985118 小时前
DVWA靶场通关——SQL Injection篇
数据库·sql
Yawesh_best18 小时前
告别系统壁垒!WSL+cpolar 让跨平台开发效率翻倍
运维·服务器·数据库·笔记·web安全
蒋士峰DBA修行之路18 小时前
实验二十八 SQL PATCH调优
数据库·sql·gaussdb