connect by prior start with 經常會被用到一個表中存在遞歸關係的時候。比如我們經常會將一個比較複雜的目錄樹存儲到一個表中。或者將一些部門存儲到一個表中,而這些部門互相有隸屬關係。這個時候你就會用到connect by prior start with。
表結構:
create table TB_ORG
(
ORGID VARCHAR2(50) not null,
ORGNAME VARCHAR2(100),
ORGPARENT VARCHAR2(50),
)
SQL> select orgid,ORGPARENT from tb_org order by ORGid desc;
ORGID ORGPARENT
----------------- --------------------------------------------------
top_org
newsroom top_org
sjgt newsroom
bgjsyj newsroom
bgjs newsroom
test52 bgjsyj
test36 bgjsyj
test3 bgjs
test2 sjgt
test1 sjgt
tes4t1 bgjs
--子取父
select * from tb_org CONNECT BY PRIOR orgparent=orgid START WITH orgid='newsroom'
-----子取父變形 ()
select * from tb_org CONNECT BY PRIOR orgparent=orgid START WITH orgparent='newsroom'
--父取子(結果中沒有父這條記錄)
select * from tb_org CONNECT BY PRIOR orgid=orgparent START WITH orgparent='newsroom'
-----父取子變形(多了父這一級)
select * from tb_org connect by prior orgid=orgparent start with orgid ='newsroom'
注意orgid=orgparent 和orgparent=orgid
轉自:http://blog.csdn.net/kenny1985/article/details/3980583