Greenplum (PostgreSql) using a tree structure with recursive implement recursive queries and insert a new table

This code is an alternative object of the connect by Oracle's statement, and the latter path and achieve idleaf function.

Text began:

  Suppose the table org, the field has id (number), name (name), pid (the higher number), the uppermost recording pid is empty.

Such as:

id     name     pid

Group 1 null

Ministry of Finance 1 2

3 Administration 1

4 accounting host 2

 

  Achieve the target table neworg:

id name pid pname path_id path_name leve is_leaf (leaf node)

1 Group null null / 1/10 Group

Group Finance Department 2 1/1/2 / Group / Ministry of Finance 20

3 Group Administration Department 1/1/3 / group / Administration 21

Sponsored by the Ministry of Finance Accounting 4 2/1/2 / Group / Ministry of Finance / Accountant 21

 

  Code handwriting, spelling mistakes, please forgive me if:

the SET gp_recursive_cte_prototype to ture; - part of the low version greenplum must be added 
INSERT  INTO NewOrg 
( 
    the above mentioned id, name, pid, path_id, path_name, leve, is_leaf 
) 
with recursive This result_ AS  - recursive beginning of the body 
(
     the SELECT the above mentioned id - The first is the top-level node 
    , name 
    , PID 
    , Cast (ID AS  VARCHAR ( 100 )) AS path_id - ensure the same format as the target table 
    , Cast (name AS  VARCHAR ( 500)) AS path_name 
    , . 1  AS leve
     from ORG 
     WHERE ID =  ' . 1 '  - Specifies the position of the top node 
    Union  All  - The following is a lower node 
    SELECT org.id 
    , org.name 
    , org.pid 
    , Cast (r.id ||  ' / '  || org.id AS  VARCHAR ( 100 )) AS path_id - slash splicing 
    , Cast (r.name ||  '/ '  || org.name AS  VARCHAR ( 500 )) AS path_name - slash splicing 
    , r.leve +  . 1  AS leve - every time recursion. 1 + 
    , 0  AS is_leaf
     from result_ R & lt - note that this is result_ 
    the Join ORG oN org.pid = r.id - specifies the parent-child relationship, where attention is actually the Join Inner 
    the wHERE  1  =  1  - there are other conditions can be added here 
)
 - then where can query result_ the same time processing is_leaf field 
selectt.id, t.name, t.pid, org.name AS pname 
, ' / '  || t.path_id AS path_id - formatting avoid missing top slash 
, ' / '  || t.path_name AS path_name 
, T .leve 
, Case  when TRIM (t.id) in ( SELECT  DISTINCT a1.pid from ORG A1) the then  ' 0 '  the else  ' . 1 '  and  aS id_leaf - determines whether a leaf node, when writing table where a large amount of data efficiency is low, consider extra with the new.
from result_ t
 left  the Join ORG ON t.pid = org.id - again related information about the parent

 

Guess you like

Origin www.cnblogs.com/lbhqq/p/11577024.html