I was going through some previous posts on CONNECT BY usage. What I need to find is that what to do if I want to get all the parents (i.e, up to root) and just one child for a node, say 4.
It seems Like I will have to use union of the following two:-
SELECT *
FROM hierarchy
START WITH id = 4
CONNECT BY id = PRIOR parent
union
SELECT *
FROM hierarchy
WHERE LEVEL =<2
START WITH
id = 4
CONNECT BY
parent = PRIOR id
Is there a better way to do this, some workaround that is more optimized?
You should be able to do this using a sub-select (and DISTINCT
) to find all children of 4
:
Select Distinct *
From hierarchy
Start With id In ( Select id
From hierarchy
Where parent = 4 )
Connect By id = Prior parent
Using UNION
you could at least remove the CONNECT BY
from your second query:
Select *
From hierarchy
Start With id = 4
Connect By id = Prior parent
Union
Select *
From hierarchy
Where parent = 4
Never use SELECT *
, always name the columns you actually need. This makes your query easier to read, to maintain and to optimize.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With