Recursive query of single table tree structure in postgressql

In a single table, the pid field is used to represent the parent node id. When querying, it is required to find a node and all its child nodes according to the id.

The table structure of the test is as follows:

create table test2(
  id integer,
  name varchar,
  pid integer
);

 

Insert test data

 

insert into test2 values(1,'A',null);
insert into test2 values(2,'A1',1);
insert into test2 values(3,'A2',1);
insert into test2 values(4,'B',2);

 The tree structure is as follows:

1    A

2 ---- A1

3    --------B

4 ----A2

A simple query to find the parent node and all its child nodes according to the node ID (for example, check the node with id=2)

with recursive t(id, name, pid) as (
    select id, name, pid from test2 where id=2
    union all
    select t2.id, t2.name, t2.pid from test2 t2
    join t on t2.pid=t.id
)
select id, name, pid from t order by id;

 Query with path and tree node depth

with recursive t(id, name, pid, path, depth) as (
    select id, name, pid, array[id] as path, 1 as depth
    from test2 where pid is null
    union all
    select t2.id, t2.name, t2.pid, t.path || t2.id, t.depth + 1 as depth
    from test2 t2
    join t on t2.pid=t.id
)
select id, name, pid, path, depth from t order by path;

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326488044&siteId=291194637