前言
說(shuō)到Oracle中的遞歸查詢(xún)語(yǔ)法,我覺(jué)得有一些數(shù)據(jù)庫(kù)基礎(chǔ)的童鞋應(yīng)該都知道,做項(xiàng)目的時(shí)候應(yīng)該也會(huì)用到,下面本文就來(lái)介紹下關(guān)于Oracle通過(guò)遞歸查詢(xún)父子兄弟節(jié)點(diǎn)的相關(guān)內(nèi)容,分享出來(lái)供大家參考學(xué)習(xí),下面話(huà)不多說(shuō)了,來(lái)一起看看詳細(xì)的介紹吧。
方法如下:
1、查詢(xún)某節(jié)點(diǎn)下所有后代節(jié)點(diǎn)(包括各級(jí)父節(jié)點(diǎn))
// 查詢(xún)id為101的所有后代節(jié)點(diǎn),包含101在內(nèi)的各級(jí)父節(jié)點(diǎn) select t.* from SYS_ORG t start with id = '101' connect by parent_id = prior id
2、查詢(xún)某節(jié)點(diǎn)下所有后代節(jié)點(diǎn)(不包含各級(jí)父節(jié)點(diǎn))
select t.* from SYS_ORG t where not exists (select 1 from SYS_ORG s where s.parent_id = t.id) start with id = '101'connect by parent_id = prior id
3、查詢(xún)某節(jié)點(diǎn)所有父節(jié)點(diǎn)(所有祖宗節(jié)點(diǎn))
select t.* from SYS_ORG t start with id = '401000501' connect by prior parent_id = id
4、查詢(xún)某節(jié)點(diǎn)所有的兄弟節(jié)點(diǎn)(親兄弟)
select * from SYS_ORG t where exists (select * from SYS_ORG s where t.parent_id=s.parent_id and s.id='401000501')
5、查詢(xún)某節(jié)點(diǎn)所有同級(jí)節(jié)點(diǎn)(族節(jié)點(diǎn)),假設(shè)不設(shè)置級(jí)別字段
with tmp as( select t.*, level leaf from SYS_ORG t start with t.parent_id = '0' connect by t.parent_id = prior t.id)select * from tmp where leaf = (select leaf from tmp where id = '401000501');
這里使用兩個(gè)技巧,一個(gè)是使用了level來(lái)標(biāo)識(shí)每個(gè)節(jié)點(diǎn)在表中的級(jí)別,還有就是使用with語(yǔ)法模擬出了一張帶有級(jí)別的臨時(shí)表
6、查詢(xún)某節(jié)點(diǎn)的父節(jié)點(diǎn)及兄弟節(jié)點(diǎn)(叔伯節(jié)點(diǎn))
with tmp as( select t.*, level lev from SYS_ORG t start with t.parent_id = '0' connect by t.parent_id = prior t.id) select b.*from tmp b,(select * from tmp where id = '401000501' and lev = '2') awhere b.lev = '1'union allselect *from tmpwhere parent_id = (select distinct x.id from tmp x, --祖父 tmp y, --父親 (select * from tmp where id = '401000501' and lev > '2') z --兒子 where y.id = z.parent_id and x.id = y.parent_id);
這里查詢(xún)分成以下幾步。
首先,將全表都使用臨時(shí)表加上級(jí)別;
其次,根據(jù)級(jí)別來(lái)判斷有幾種類(lèi)型,以上文中舉的例子來(lái)說(shuō),有三種情況:
(1)當(dāng)前節(jié)點(diǎn)為頂級(jí)節(jié)點(diǎn),即查詢(xún)出來(lái)的lev值為1,那么它沒(méi)有上級(jí)節(jié)點(diǎn),不予考慮。
(2)當(dāng)前節(jié)點(diǎn)為2級(jí)節(jié)點(diǎn),查詢(xún)出來(lái)的lev值為2,那么就只要保證lev級(jí)別為1的就是其上級(jí)節(jié)點(diǎn)的兄弟節(jié)點(diǎn)。
(3)其它情況就是3以及以上級(jí)別,那么就要選查詢(xún)出來(lái)其上級(jí)的上級(jí)節(jié)點(diǎn)(祖父),再來(lái)判斷祖父的下級(jí)節(jié)點(diǎn)都是屬于該節(jié)點(diǎn)的上級(jí)節(jié)點(diǎn)的兄弟節(jié)點(diǎn)。
最后,就是使用union將查詢(xún)出來(lái)的結(jié)果進(jìn)行結(jié)合起來(lái),形成結(jié)果集。
總結(jié)
以上就是這篇文章的全部?jī)?nèi)容了,希望本文的內(nèi)容對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,如果有疑問(wèn)大家可以留言交流,謝謝大家對(duì)VeVb武林網(wǎng)的支持。
新聞熱點(diǎn)
疑難解答
圖片精選