oracle connect by用法補充__oracle

來源:互聯網
上載者:User
1、基本文法

select * from table [start with condition]    connect by [prior] id=parentid
一般用來尋找存在父子關係的資料,也就是樹形結構的資料;其返還的資料也能夠明確的區分出每一層的資料。
 start with condition 是用來限制第一層的資料,或者叫根節點資料;以這部分資料為基礎來尋找第二層資料,然後以第二層資料尋找第三層資料以此類推。 connect by [prior] id=parentid 這部分是用來指明oracle在尋找資料時以怎樣的一種關係去尋找;比如說尋找第二層的資料時用第一層資料的id去跟表裡面記錄的parentid欄位進行匹配,如果這個條件成立那麼尋找出來的資料就是第二層資料,同理尋找第三層第四層…等等都是按這樣去匹配。


prior還有一種用法:

select * from table [start with condition]    connect by id= [prior] parentid
這種用法就表示從下往上尋找資料,可以理解為從葉子節點往上尋找父級幾點,用第一層資料的parentid去跟表記錄裡面的id進行匹配,匹配成功那麼尋找出來的就是第二層資料;上面的那種就是從父級節點往下尋找葉子節點。

其他特性
    level關鍵字,代表樹形結構中的層級編號;第一層是數字1,第二層數字2,依次遞增。
    CONNECT_BY_ROOT方法,能夠擷取第一層集結點結果集中的任意欄位的值;例CONNECT_BY_ROOT(欄位名)。
2、下面來貼兩個例子

2.1 從根節點尋找葉子節點

select t.*, level, CONNECT_BY_ROOT(id)  from tab_test t start with t.id = 0connect by prior t.id = t.fid;

2.2 從葉子節點尋找上層節點

--第一種,修改prior關鍵字位置select t.*, level, CONNECT_BY_ROOT(id)  from tab_test t start with t.id = 4connect by t.id = prior t.fid;--第二種,prior關鍵字不動 調換後面的id=fid邏輯關係的順序select t.*, level, CONNECT_BY_ROOT(id)  from tab_test t start with t.id = 4connect by prior t.fid = t.id;
3、寫幾個平常用到的其他一些用法

3.1 產生數字序列結果集 使用rownum實現1到10的序列。

select rownum from dual connect by rownum<=10;

使用level實現1到10的序列。
select level from dual connect by level<=10;

3.2 查詢目前時間往前的12周的開始時間、結束時間、第多少周
select sysdate - (to_number(to_char(sysdate - 1, 'd')) - 1) -       (rownum - 1) * 7 as startDate,       sysdate + (7 - to_number(to_char(sysdate - 1, 'd'))) -       (rownum - 1) * 7 as endDate,       to_number(to_char(sysdate, 'iw')) - rownum + 1 as weekIndex  from dualconnect by level<= 12;--將level改成rownum可以實現同樣的效果

3.3 字串分割,由一行變為多行
select REGEXP_SUBSTR('01#02#03#04', '[^#]+', 1, rownum) as newport     from dual connect by rownum <= REGEXP_COUNT('01#02#03#04', '[^#]+');

參考:http://blog.csdn.net/wang_yunj/article/details/51040029

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.