I have table with self-related foreign keys and can not get how I can receive firs child or descendant which meet condition. My_table structure is:
| id | parent_id | type |
|---|---|---|
| 1 | null | union |
| 2 | 1 | group |
| 3 | 2 | group |
| 4 | 3 | depart |
| 5 | 1 | depart |
| 6 | 5 | unit |
| 7 | 1 | unit |
I should for id 1 (union) receive all direct child or first descendant, excluding all groups between first descendant and union. So in this example as result I should receive:
| id | type |
|---|---|
| 4 | depart |
| 5 | depart |
| 7 | unit |
id 4 because it's connected to union through group with id 3 and group with id 2 and id 5 because it's connected directly to union.
I've tried to write recursive query with condition for recursive part: when parent_id = 1 or parent_type = 'depart' but it doesn't lead to expected result
with recursive cte AS (
select b.id, p.type_id
from my_table b
join my_table p on p.id = b.parent_id
where b.id = 1
union
select c.id, cte.type_id
from my_table c
join cte on cte.id = c.parent_id
where c.parent_id = 1 or cte.type_id = 'group'
)

group? But you don't want to get all the descendants?