ORACLE樹形結構查詢

2021-04-27 11:47:03 字數 1606 閱讀 7803

在oracle資料庫查詢中,我們經常會遇到對樹型結構表的查詢,這是個麻煩的問題。下面給大家介紹一種sql語句,實現遞迴查詢。語法如下:

select 欄位1,欄位2,欄位3,。。。

from 表名

start with 條件1

connect by prior 條件2

where 條件3;

下面舉乙個例子,有這樣一張表:

表dg_test

parent_id                     child_id                         id_desc

0000                             1001                            rows0

0000                             1002                            rows1

0000                             1003                            rows2

0000                             1004                            rows3

1001                             2001                            rows4

1001                             2002                            rows5

1002                             2003                            rows6

1003                             2004                            rows7

2001                             3001                            rows8

3001                             4001                            rows9

使用如下sql 語句:

select * from dg_test start with parent_id = '1001' connect by prior child_id = parent_id;

查詢結果如下:

parent_id                     child_id                         id_desc

1001                             2001                            rows4

1001                             2002                            rows5

2001                             3001                            rows8

3001                             4001                            rows9

Oracle查詢樹形結構

oracle中的select語句可以用start with.connect by prior子句實現遞迴查詢,connect by 是結構化查詢中用到的,其基本語法是 select from tablename start with cond1 connect by cond2 where cond...

oracle樹形結構查詢

最近用到了oracle的start with函式,所以在這裡簡單的記錄一下 首先可以造乙個表字段很簡單,如下 create table create table code id number,name varchar2 20 pid number tablespace tsdacns pctfree...

oracle樹形結構實行查詢

oracle提供了一種樹形結構用來實現層次查詢 start with 指定查詢的根行。connect by 指定父行和子行的關係。prior 引用父行。為測試方便,使用如下demo 建立資料庫表treetable create table treetable id number primary ke...