Oracle樹形查詢

2021-06-02 19:06:53 字數 987 閱讀 3506

基本語法

select...from tabename start with cond1 connect by  prior cond2 where cond2

注:cond1是根節點的限定語句

cond2是連線條件,其中prior表示上一條記錄,指該記錄的父親是上一條記錄

cond3是過濾條件

構造環境:不說***

create table family(

id integer,

parentid integer,

name varchar2(50)

)insert into family values(0,0,'a')

insert into family values(1,0,'b')

insert into family values(2,1,'c')

insert into family values(3,1,'d')

insert into family values(4,1,'e')

insert into family values(5,1,'f')

例一:通過根節點遍歷子節點

--查詢父親等於1的所有子的資訊

select * from family start with parentid=1 connect by prior id=parentid

例二:通過子節點向根節點追溯

select * from family start with id=5 connect by prior parentid=id

注:如果報ora-01436:使用者資料庫中的coonect by迴圈,則將第一條資料中的parentid改為null,否則loop迴圈找parentid就找不到了!

擴充套件:通過level 關鍵字查詢所在層次

select t.*,level from family t start with parentid=1 connect by prior id=parentid --表必須用別名

oracle 樹形查詢

1.1 簡單的樹形查詢 select empno as 員工編碼,ename as 姓名,mgr as 主管,prior ename as 主管姓名 1.2 根節點,分支節點,葉節點 level 返回所在的等級 connect by isleaf 如果當前節點下沒有其他節點返回1,其他返回0。sel...

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...