递归查询分为父子查询和子父查询。
父子查询: 根据父 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: MySQL :: MySQL 8.0 Reference Manual :: 13.2.15 WITH (Common Table Expressions) https://dev.mysql.com/doc/refman/8.0/en/with.html#common-table-expressions-recursive