Greenplum(PostgreSql)使用 with recursive 实现树形结构递归查询并插入新表

时间:2019-09-24
本文章向大家介绍Greenplum(PostgreSql)使用 with recursive 实现树形结构递归查询并插入新表,主要包括Greenplum(PostgreSql)使用 with recursive 实现树形结构递归查询并插入新表使用实例、应用技巧、基本知识点总结和需要注意事项,具有一定的参考价值,需要的朋友可以参考一下。

本代码目的是替代Oracle的connect by语句,并实现后者的path和idleaf功能。

正文开始:

  假设表org,字段有 id(编号),name(名称),pid(上级编号), 最上级的记录pid为空。

如:

id     name     pid

1     集团       null

2     财务部     1

3     行政部     1

4     主办会计  2

  实现目标表neworg:

id    name    pid      pname    path_id       path_name                   leve      is_leaf(叶子节点)

1     集团       null    null            /1                 /集团                              1              0

2     财务部    1       集团          /1/2              /集团/财务部                   2             0

3     行政部     1       集团         /1/3              /集团/行政部                   2             1

4     主办会计   2      财务部     /1/2              /集团/财务部/主办会计    2             1

  代码手写,如有拼写错误请见谅:

set gp_recursive_cte_prototype to ture; -- 部分低版本greenplum必须加
insert into neworg
(
    id, name, pid, path_id, path_name, leve, is_leaf
)
with recursive result_ as -- 递归主体开始
(
    select id -- 首先是顶层节点
    , name
    , pid
    , cast(id as varchar(100)) as path_id -- 保证格式与目标表相同
    , cast(name as varchar(500)) as path_name
    , 1 as leve
    from org 
    where id = '1' -- 指定顶层节点位置
    union all -- 下面是下层节点
    select org.id
    , org.name
    , org.pid
    , cast(r.id || '/' || org.id as varchar(100)) as path_id -- 拼接时加上斜杠
    , cast(r.name || '/' || org.name as varchar(500)) as path_name -- 拼接时加上斜杠
    , r.leve + 1 as leve -- 每递归一次 + 1
    , 0 as is_leaf
    from result_ r -- 注意这里是 result_
    join org on org.pid = r.id -- 指定父子关系,这里注意其实是inner join 
    where 1 = 1 -- 有其他条件可加在这里
)
-- 然后这里可以查询result_了,同时加工is_leaf字段
select t.id, t.name, t.pid, org.name as pname
, '/' || t.path_id as path_id -- 格式化避免顶层缺少斜杠
, '/' || t.path_name as path_name
, t.leve
, case when trim(t.id) in (select distinct a1.pid from org a1 ) then '0' else '1' and as id_leaf -- 判断是否叶子节点,写在此处当表数据量较大时效率较低,可以考虑额外跟新。
from result_ t
left join org on t.pid = org.id -- 再关联一下父级信息

原文地址:https://www.cnblogs.com/lbhqq/p/11577024.html