递归查询分为父子查询和子父查询。
父子查询:
根据父 id 查询下面所有子节点数据;
子父查询:
根据子 id 查询上面所有父节点数据;
下边就利用 mysql8 新增语法实现递归查询,表结构及数据如下图:
父子查询:
with recursive r as
(
select id,name from c where id=1
union all
select c.id,CONCAT(r.name, '>', c.name) as name from c,r where r.id = c.ParentID
)
select id,name from r order by id;
查询结果如下:
子父查询:
with recursive r as
(
select * from c where id =11
union all
select c.* from c,r where c.id=r.ParentID
)
select * from r order by id;
查询结果如下:
via:
mysql8利用CTE特性实现递归查询 - 膨胀的面包
https://blog.wangtwothree.com/code/179.html