oracle樹形結構查詢

2021-10-05 01:37:58 字數 1552 閱讀 9080

最近用到了oracle的start with函式,所以在這裡簡單的記錄一下:

首先可以造乙個表字段很簡單,如下:

-- create table

create table code

( id number,

name varchar2(20),

pid number

)tablespace tsdacns

pctfree 10

initrans 1

maxtrans 255

storage

( initial 64k

next 1m

minextents 1

maxextents unlimited

);

建立了乙個code表,表裡只有三個字段,分別是id,name,pid,插入以下資料:

insert into code (id, name, pid)

values (1, '中國', null);

insert into code (id, name, pid)

values (2, '河南', 1);

insert into code (id, name, pid)

values (3, '河北', 1);

insert into code (id, name, pid)

values (4, '平頂山', 2);

insert into code (id, name, pid)

values (5, '漯河', 2);

insert into code (id, name, pid)

values (6, '安陽', 2);

insert into code (id, name, pid)

values (7, '唐山', 3);

insert into code (id, name, pid)

values (8, '保定', 3);

insert into code (id, name, pid)

values (9, '天津', 3);

以上為插入的資料,通過以下sql可以查詢出帶有層級的結果:

select * from code start with id = 1 connect by prior id = pid
查詢出來的效果是這樣的:

再來看看預設的查詢效果:

接下來對這個函式進行簡單的解釋,start with是根節點的限定語句,當然可以放寬條件,有多個根節點,取到多棵樹。connect by prior是連線條件,其中prior表示上一條記錄,例如當前例子的connect by prior id = pid,意思就是上條記錄的id是本條資料的父級id。

ORACLE樹形結構查詢

在oracle資料庫查詢中,我們經常會遇到對樹型結構表的查詢,這是個麻煩的問題。下面給大家介紹一種sql語句,實現遞迴查詢。語法如下 select 欄位1,欄位2,欄位3,from 表名 start with 條件1 connect by prior 條件2 where 條件3 下面舉乙個例子,有這...

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 指定查詢的根行。connect by 指定父行和子行的關係。prior 引用父行。為測試方便,使用如下demo 建立資料庫表treetable create table treetable id number primary ke...