在oracle中遇到了Start With查詢語句,經過查詢資料瞭解現在總結一下.
參考文章:https://www.cnblogs.com/zyzdisciple/p/7873584.html
首先我們可以新建一個demo表做測試
create table DEMO ( ID varchar2(10) primary key, DSC varchar2(100), PID varchar2(10) )
--插入幾條數據
Insert Into DEMO values ('00001', '中國', '-1');
Insert Into DEMO values ('00011', '陝西', '00001');
Insert Into DEMO values ('00012', '貴州', '00001');
Insert Into DEMO values ('00013', '河南', '00001');
Insert Into DEMO values ('00111', '西安', '00011'); I
nsert Into DEMO values ('00112', '咸陽', '00011');
Insert Into DEMO values ('00113', '延安', '00011');
start with的基本語法如下
SELECT ... FROM +
表名 WHERE + 條件3
START WITH + 條件1
CONNECT BY PRIOR + 條件2
條件1表示我數據的切入點,也就是我第一條數據從哪裏開始.
條件2是連接條件,其中用PRIOR表示上一條記錄,例如CONNECT BY PRIOR ID = PID,意思就是上一條記錄的ID是本條記錄的PID
條件3表示條件12執行遍歷結果之後再進行條件約束.
首先 我們查詢所有表示這樣的,
SELECT * FROM start_demo start with id = '00001' Connect By Prior id = pid
start with id = '00001' 表示切入點,也就是我的第一條數據
Connect By Prior id = pid 表示我的上一條數據的id是我當前數據的pid(如果不是就表明不是當前節點)
反之
SELECT * FROM start_demo start with id = '00113' Connect By Prior PID = id ---上一條記錄的PID是本條記錄的ID