Oracle层次化查询

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/29485627/viewspace-1251310/,如需转载,请注明出处,否则将追究法律责任。

转载于:http://blog.itpub.net/29485627/viewspace-1251310/

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值