Answer the question
In order to leave comments, you need to log in
Recursive loading of a tree with an auxiliary table, by ID, how?
Hello everyone,
I'm trying to use recursion to pull up a complete relationship tree in one query to the database, or rather the last connection point, having only one object ID.
There are two tables:
objects:
id, name
1, Test
2, Pasha
3, Masha
4, Petya,
5, Sasha
object_map:
id, parent_id, child_id
1, 1, 2
2, 2, 3
3, 4, 5
When querying with ID 3 I want to get 3, 4 and 5.
Depth of connections theor. endless.
Whether it is possible it only by means of SQL or nevertheless it is necessary to do some requests?
I have not yet succeeded - did not come up with. I don't go beyond the first contact.
Thanks in advance.
Answer the question
In order to leave comments, you need to log in
1. The id field in the link table is redundant.
2. Here is the selection of the element and its descendants
with
recursive child_elements as (
(select id
from links
where id = 3)
union
(select lt.id
from child_elements, links as lt
where child_elements.id = lt.parent_id))
select *
from child_elements;
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question