Oracle FAQ | Your Portal to the Oracle Knowledge Grid |
Home -> Community -> Usenet -> c.d.o.misc -> Re: Help with "Connect By"
Alan Taylor wrote:
>
> I need to traverse backwards through a tree-style table and thought that
> Connect By would be the obvious method, but am having considerable
> difficulty in getting it to work. Can anyone help?
>
> The table has the following structure:
>
> create table TEST (
> Node_Id Number(10) not null,
> Section_Id Number(10) not null,
> Parent_Id Number(10) not null,
> Description VarChar2(200) not null
> )
> constraint Test_PK primary key (Node_Id, Section_Id)
> /
>
> The table contains data along the lines of:
>
> (snip data)
>
> The query that I'm trying to execute needs to extract the tree structure
> leading to a specified item, i.e. find everything LIKE "FA%" ...
>
> Buildings
> Commercial
> Farm
> Factory
>
> ...or everything LIKE "Bedroom%" ...
>
> Buildings
> Residential
> Apartment
> 1 Bedroom
> 2 Bedroom
> 3 Bedroom
> House
> 1 Bedroom
> 2 Bedroom
> 3 Bedroom
>
> Finding the required item is OK, but the problem that I'm having is
> tracing back through the tree to find all the parent items leading down
> to it (Bearing in mind that the located item could occur at any level
> within the tree).
> (snip)
Tricky.
The following will work. Just make sure you have indexes on (section_id,node_id) and on (parent_id,node_id)!
select lpad(' ',2*level,' ')||description "Desc"
from test T1
where exists
(select null from test T2
where T2.description like '%Bedroom%'
start with (T2.node_id = T1.node_id -- start from current row and T2.section_id = T1.section_id)connect by T2.node_id = prior T2.node_id and T2.parent_id = prior T2.section_id )
and parent_id = prior section_id
/
Hope this helps.
Chrysalis. Received on Mon May 26 1997 - 00:00:00 CDT