Oracle層次化查詢
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/,如需轉載,請註明出處,否則將追究法律責任。
相關文章
- 0629_層次查詢
- Oracle in 查詢優化Oracle優化
- ORACLE結構化查詢語句Oracle
- Oracle 查詢Oracle
- oracle資料庫sql查詢檢視第二次查詢很慢Oracle資料庫SQL
- oracle常用查詢Oracle
- oracle 基本查詢Oracle
- Oracle psu查詢Oracle
- 記一次詭異的Oracle查詢轉換Oracle
- oracle 精確查詢和模糊查詢Oracle
- oracle樹形查詢Oracle
- oracle 連線查詢Oracle
- Oracle 查詢轉換Oracle
- Oracle-多表查詢Oracle
- 「Oracle」Oracle高階查詢介紹Oracle
- oracle語法相容--如何透過with recursive語法來實現oracle的分層查詢Oracle
- oracle 查詢鎖 && 解鎖Oracle
- Oracle查詢鎖、解鎖Oracle
- oracle常用維護查詢Oracle
- oracle 例項表查詢Oracle
- SQL查詢語句 (Oracle)SQLOracle
- oracle表複雜查詢Oracle
- oracle update left join查詢Oracle
- Oracle阻塞會話查詢Oracle會話
- oracle最新補丁查詢Oracle
- [譯] SQLite 底層查詢原理SQLite
- Oracle:優化方法總結(關於連表查詢)Oracle優化
- pgsql查詢優化之模糊查詢SQL優化
- oracle查詢語句查詢增加一列內容Oracle
- 【VIEW】Oracle如何查詢固定檢視的定義或底層sql語句ViewOracleSQL
- Oracle 查詢多個資料Oracle
- Oracle 查詢轉換-01 or expansionOracle
- oracle連線查詢詳解Oracle
- Oracle OCP(08):使用子查詢Oracle
- 查詢優化優化
- 【SQL】Oracle查詢轉換之物化檢視查詢重寫SQLOracle
- 層級查詢並將層級拆分成多列
- 查詢最佳化——查詢樹結構
- MySQL底層概述—7.最佳化原則及慢查詢MySql