Oracle 11g R2 RSF(Recurive Subquery factoring)

來源:互聯網
上載者:User

在Oracle 11gR2之前,一般用start with和connect by來遞迴的顯示樹形結構,請看如下指令碼

select lpad(' ',2*level-1,' ') || ename ename,empno,mgr
    from emp
    where empno is not null
    connect by prior empno = mgr
    start with mgr is null


ENAME                    EMPNO        MGR
-------------------- ---------- ----------
 KING                      7839
  JONES                  7566      7839
    SCOTT                7788      7566
      ADAMS              7876      7788
    FORD                  7902      7566
      SMITH              7369      7902
  BLAKE                  7698      7839
    ALLEN                7499      7698
    WARD                  7521      7698
    MARTIN                7654      7698
    TURNER                7844      7698
    JAMES                7900      7698
  CLARK                  7782      7839
    MILLER                7934      7782
 
從11gR2開始,可以用RSF來實現
 
with sun(lvl,ename,empno,mgr) as
(select 1,lpad(' ',2*1-1,' ') || ename ename,empno,mgr from emp where mgr is null
union all
select sun.lvl+1,lpad(' ',2*lvl-1,' ') || d.ename ename,d.empno,d.mgr
from sun, emp d
where sun.empno = d.mgr)
select lvl,ename,empno,mgr from sun


      LVL ENAME                    EMPNO        MGR
---------- -------------------- ---------- ----------
        1  KING                      7839
        2  JONES                    7566      7839
        2  BLAKE                    7698      7839
        2  CLARK                    7782      7839
        3    ALLEN                    7499      7698
        3    WARD                    7521      7698
        3    MARTIN                7654      7698
        3    SCOTT                    7788      7566
        3    TURNER                  7844      7698
        3    JAMES                  7900      7698
        3    FORD                    7902      7566
        3    MILLER                  7934      7782
        4      SMITH                7369      7902
        4      ADAMS                7876      7788
 

觀察一下上述兩份輸出,用傳統的start with和connect by,結果順序類似於對emp表的前序走訪(preorder traversal);而使用RSF,則是對emp表的層次遍曆(level traversal)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.