I would like to create a full hierarcy search query in Oracle SQL database. I have a following table, called "item".
id name parent_id
1 A NULL
2 B 1
3 C 2
4 D 3
5 E 2
Input is any of a given id from id column. It should find all of this id's children, their children. As well parents and their parents. At the moment I have following query:
select distinct m.id, m.parent_id
from item m
connect by prior m.id = m.parent_id
start with m.parent_id IN (
select m.parent_id
from item m
connect by m.id = prior m.parent_id
start with m.id = 3
union
select m.parent_id
from item m
where m.parent_id = 3);
At the moment it seems to be working only so that parent which does not have parent (parent_id column is null) is not selected. Otherwise it seems to be working. Also if my given query could be simplified I would appreciate it as well.
EDIT
I think I got the desired result with following query below:
select m.id
from item m
start with m.id in (
select m.id
from item m
where connect_by_isleaf = 1
start with m.id = 3
connect by m.id = prior m.parent_id
)
connect by m.parent_id = prior m.id;
Now there is next issue I have. start with m.id = 3. Issue is that I would like to create a view out of this whole query. But as m.id value changes from query to query I cannot add it as a parameter. There's also a possibility to comment out start with m.id = 3 and then it would return all hierarchies between all items. Is there a way to create some join? E.g.: I would query all those relations of all items and then by some condition get only certain item relations.