2011-04-23 45 views
0

我有一張有州,地區,地區,建築和班級樹的表。每一行都有一個節點標識和一個父標識。我使用以下需要在Oracle下的父級子項下顯示孫子級聯查詢

select name, child node, parent id from tableA 
connect by prior child node = parent id 

我得到:

CA 
    CENTRAL REGION 
    FRESNO DISTRICT 
    ST Jim BUILDING 
    ST joe BUILDING 
    st tom BUILDING 
    st sue BUILDING 
     JIMS CLASS 
     JOES CLASS 
     TOM CLASS 
     SUE CLASS 

問題是,在建築級別的所有建築都陸續上市,然後所有的類此起彼伏。不過,我想列出建設和類是那麼接下來建築物的父如下

FRESNO DISTRICT 
    st jim building 
     jims class 
    st joes building 
     joes class... 

節點ID和父ID是正確的,它只是所有兒童都列出了父母那麼所有的孩子那個孩子。它沒有顯示哪個孩子跟父母一起去。

我想表明從上而下,如CA,中部地區,弗雷斯諾地區,聖喬大廈,瑪麗女士類樹,女士

回答

3

的等級秩序應該被保留,除非您使用ORDER BY沒有SIBLINGS關鍵字。

select name, id, parent_id 
from tableA 
connect by prior id = parent_id 
start with parent_id is null 
order siblings by name; 

使用此數據:

create table tableA(id number, name varchar2(100), parent_id number); 

insert into tableA 
select 1 id, 'CA' name, null parent_id from dual union all 
select 2, 'CENTRAL REGION', 1 from dual union all 
select 3, 'FRESNO DISTRICT', 2 from dual union all 
select 4, 'ST Jim BUILDING', 3 from dual union all 
select 5, 'ST joe BUILDING', 3 from dual union all 
select 6, 'st tom BUILDING', 3 from dual union all 
select 7, 'st sue BUILDING', 3 from dual union all 
select 8, 'JIMS CLASS', 4 from dual union all 
select 9, 'JOES CLASS', 5 from dual union all 
select 10, 'TOM CLASS', 6 from dual union all 
select 11, 'SUE CLASS', 7 from dual;