



























#编程技术 2022-02-08 17:18:26 | 全文 184 字,阅读约需 1 分钟 | 加载中... 次浏览
递归查询分为父子查询和子父查询。
父子查询: 根据父 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
© 2023 膨胀自留地 | 鲁ICP备2021021876号-2 | SiteMap | RSS
Powered by Hugo 0.121.0. 247 articles in total.
Last Update:2025-07-23 10:02:48
×
此内容由惯性聚合(RSS阅读器)自动聚合整理,仅供阅读参考。 原文来自 — 版权归原作者所有。