views:

201

answers:

1

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?

+3  A: 

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.

Peter Lang
Its sometimes really funny when we overlook some obvious things. The union part was SO obvious but I think I was too much preoccupied with the CONNECT BY clause. And yes, I know not to use SELECT * but was just trying to shorten the text. :)Thanks.
s khan