oracle數據庫SQL開發之層次查詢

oracle數據庫SQL開發之層次查詢

一、自然樹結構

如emp表中數據
在這裏插入圖片描述
關係樹結構
在這裏插入圖片描述

二、層次查詢

語法結構:

select [level], column, expr...
from table
[where condition(s)]
[start with condition(s)]
[connect by prior column1=column2] ;

level:節點的層次,僞列,由查詢的起點開始算起爲1,依次類推。
– from table:指定表、視圖或包含列的快照,你只能從單獨的一個表中選擇。
–where: 限制返回的行。
– condition(s):是一個比較式。
start with :**指定層次的根行 (起點)。**這個子句對於一個正確的分級查詢是必須的。
connect by prior指定存在父與子行的關係列。對於分級查詢該子句是必須的。

connect by prior 語句中的
在這裏插入圖片描述
emp員工表中經理號mgr、員工號empno
從頂向下

select empno, ename, job, mgr
from emp
start with ename = 'KING'
connect by prior empno = mgr;--parent key = child key:經理的員工編號=員工的經理編號

從底向上

select empno, ename, job, mgr
from emp
start with empno=  7876
connect by prior mgr = empno;--child key=parent key:員工的經理編號=經理的員工編號

三、修剪分枝

1.用 where 子句中條件去除一個結點
where ename <>'Higgins’
在這裏插入圖片描述
2.用 connect by 子句中條件去除一個分支
…connect by prior empno = mgr and ename <> ‘Higgins’
在這裏插入圖片描述

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章