栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 面试经验 > 面试问答

基于邻接表的递归查询递归数据

面试问答 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

基于邻接表的递归查询递归数据

您对第一级的查询(此处

depth
与表格区别)应如下所示:

select l.name, h.child_id, 1 as depth from level ljoin level_hierarchy h on l.id = h.child_id where h.parent_id is null;   name   | child_id | depth ----------+----------+------- Level1_a |        1 |     1(1 row)

请注意的正确用法

is null
(不要总是
=
与进行比较)。
null``null

您可以将以上内容用作递归cte中的初始查询:

with recursive recursive_query as (    select l.name, h.child_id, 1 as depth     from level l    join level_hierarchy h on l.id = h.child_id     where h.parent_id is nullunion all    select l.name, h.child_id, depth + 1    from level l    join level_hierarchy h on l.id = h.child_id    join recursive_query r on h.parent_id = r.child_id)select *from recursive_query-- where depth = 2   name   | child_id | depth ----------+----------+------- Level1_a |        1 |     1 Level2_b |        3 |     2 Level2_a |       19 |     2 Level3_a |        4 |     3 Level3_b |        5 |     3 Level4_a |        6 |     4 Level4_b |        7 |     4(7 rows)


转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/495300.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号