oracle 樹形 sql查詢例子

來源:互聯網
上載者:User

通過此SQL語句 

select  * from tree

 查看未經處理資料如下:

我們要想得到如下的一個樹形查詢結果如所示(包含 ROOT, LEVEL, IS_LEAF,  PATH 四個欄位):

 

可執行如下SQL語句:

select connect_by_root(child_col) root, level , decode(connect_by_isleaf,0,'No',1,'Yes') is_leaf, sys_connect_by_path(child_col,'/') pathfrom treestart with parent_col is null connect by prior child_col=parent_col;

 

 

樹形查詢的重點在於  start with ...  connect by prior .... 語句
以及 connect_by_root ,connect_by_isleaf,sys_connect_by_path這三個函數, decode是一般常用的函數。

 

 

其他參考:http://www.cnblogs.com/tongzhenhua/archive/2008/09/23/1297253.html

 

 

動態查詢語句例子:

declare n_rows number; v_sql_stmt varchar2(50); v_table_name varchar2(20); v_name varchar2(20);begin v_table_name := 'tree'; v_sql_stmt := 'select count(*) from ' || v_table_name || ' where parent_col = :1'; v_name := 'asia'; dbms_output.put_line(v_sql_stmt); execute immediate v_sql_stmt into n_rows using v_name; dbms_output.put_line('The number of rows of' || v_table_name || 'is ' || n_rows);end;

 

聯繫我們

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