oracle 樹狀查詢,查詢根節點

2021-08-25 06:57:01 字數 1018 閱讀 4908

1、第一種方法

sql> select to_number(substr(path, 2, instr(path, '/', 2) - 2)) root_id, id

2 from

3 (4 select sys_connect_by_path(id, '/') || '/' path, id

5 from test

6 where rownum < 10

7 connect by prior id = fid

8 )9 ;

root_id id ------------ ------------

1 11 2

1 200516

1 2005859

1 2005862

1 2005864

1 2005866

1 2005867

1 2005865

已選擇9行。

2、第二種方法

select to_number(substr(sys_connect_by_path(id,'/') || '/',2,instr(sys_connect_by_path(id,'/') || '/','/','2')-2)) root_id from test start with id = 1 connect by prior id = fid;

3、第三種方法

select to_number(substr(path,2,instr(path,'/','2')-2)) root_id from (select sys_connect_by_path(id,'/') || '/' path from test start with id=1 connect by prior id = fid);

測試第三中方法的效率比較高。

以上是oracle9i提供的演算法

oracle 10g提供了 偽列或者說(函式)

select connect_by_root(id),id from test connect by prior id = fid;

最快

SQL查詢根節點

地點 廣東深圳 create table tb id varchar 3 pid varchar 3 name varchar 10 insert into tb values 001 null 廣東省 insert into tb values 002 001 廣州市 insert into tb...

Oracle 樹狀查詢

筱公尺加步槍 posted 2010年8月18日 23 01 in 資料庫 with tags oracle 樹狀,950 閱讀 在實際應用中,經常利用資料庫儲存樹狀結構的資料,通常用一張表中的兩個字段表示,乙個是自身的id,乙個是儲存父類的id。在這樣具有這種關係中的資料,要求查出的資料具有我們想...

oracle 樹狀查詢

connect by 是結構化查詢中用到的,其基本語法是 select from tablename start with 條件1 connect by 條件2 where 條件3 例 select from table start with org id hbhqfwgwpy connect by...