Oracle層次化查詢

孤竹星發表於2017-09-12
P { margin-bottom: 0.21cm; }

Oracle層次化查詢


(1) 樹狀模型

假如有一個市場模型,其中一級市場是中國,二級市場是省份,三級市場是各個省下面的市,四級市場是各個市下面的縣。那麼可以建立表market


create table market(market_id number(2), market_name varchar2(10), parent_market_id number(2));


insert all

into market values(1, 'China', 0)

into market values(2, 'Shan Xi', 1)

into market values(3, 'Shan Dong', 1)

into market values(4, 'Fu Jian', 1)

into market values(5, 'Tai Yuan', 2)

into market values(6, 'Yang Quan', 2)

into market values(7, 'Qi Zhou', 2)

into market values(8, 'Qing Dao', 3)

into market values(9, 'Ji Nan', 3)

into market values(10, 'Yan Tai', 3)

into market values(11, 'Xia Men', 4)

into market values(12, 'Fu Zhou', 4)

into market values(13, 'Quan Zhou', 4)

into market values(14, 'Gu Jiao', 5)

into market values(15, 'Yang Qu', 5)

into market values(16, 'Qing Xu', 5)

select * from dual;


(2) 層次化查詢

select market_id, market_name

from market

start with market_name = 'Shan Xi'

connect by prior market_id = parent_market_id;


MARKET_ID MARKET_NAME

---------- ------------------------------

2 Shan Xi

5 Tai Yuan

14 Gu Jiao

15 Yang Qu

16 Qing Xu

6 Yang Quan

7 Qi Zhou


7 rows selected.


這裡的搜尋規則為:從'Shan Xi'節點開始搜尋、前一個節點的market_id等於下一個節點的parent_markket_id


(3) 相關函式

顯示搜尋路徑的函式為

sys_connect_by_path(列名,分隔符)


示例:

select market_id, market_name, sys_connect_by_path(market_name, '/') as market_path

from market

start with market_name = 'Gu Jiao'

connect by prior parent_market_id = market_id;


MARKET_ID MARKET_NAM MARKET_PATH

---------- ---------- ----------------------------------------

14 Gu Jiao /Gu Jiao

5 Tai Yuan /Gu Jiao/Tai Yuan

2 Shan Xi /Gu Jiao/Tai Yuan/Shan Xi

1 China /Gu Jiao/Tai Yuan/Shan Xi/China


這裡可以利用max()函式來獲得完整的路徑:

select max(sys_connect_by_path(market_name, '/')) market_path

from market

start with market_name = 'Gu Jiao'

connect by prior parent_market_id = market_id;


MARKET_PATH

----------------------------------------

/Gu Jiao/Tai Yuan/Shan Xi/China

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/28282660/viewspace-2144872/,如需轉載,請註明出處,否則將追究法律責任。

相關文章