D
D
Dmitry Bystrov2021-08-06 18:54:44
PostgreSQL
Dmitry Bystrov, 2021-08-06 18:54:44

How to write a recursive query?

There is a hierarchy of categories:

610d5a2266bbb551644630.png
We need a query that will allow us to get a table of the form:

610d5ac62f652126607686.png
where childs is the id of child categories, including the parent category.

Table structure

Table structure

create table landcategory (   
  id serial,
  code varchar(20),
  name varchar(400),  
  parent_id bigint
);

insert into landcategory(code, name, parent_id) values('1', 'Земли населенных пунктов', null);
insert into landcategory(code, name, parent_id) values('1-1', 'Подкатегория 1-1', 1);
insert into landcategory(code, name, parent_id) values('1-2', 'Подкатегория 1-2', 1);
insert into landcategory(code, name, parent_id) values('1-2-1', 'Подкатегория 1-2', 3);

Answer the question

In order to leave comments, you need to log in

1 answer(s)
G
galaxy, 2021-08-06
@Teshuhack

Well, something like this (outputs for each row with parent_id = null):

with recursive cat as (
  select id, id top from landcategory where parent_id is null
  union
  select lc.id, top from landcategory lc join cat on (cat.id = lc.parent_id)
)
select lc.*, childs from landcategory lc join (
  select top, array_agg(id) childs from cat
   group by 1
) t on (t.top = lc.id)

https://www.db-fiddle.com/f/9gQNjVwLn3W11pnCcr8NEs/0

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question