SQL 遞迴寫法 (oracle db2)

2021-06-03 20:41:44 字數 2424 閱讀 4326

oracle 遞迴方式:

一、建表 create table users.tbl_test ( id number, name varchar2(100 byte), pid number default 0 ) insert into tbl_test(id,name,pid) values('1','10','0'); insert into tbl_test(id,name,pid) values('2','11','1' insert into tbl_test(id,name,pi

一、建表

create table users.tbl_test

id    number,

name  varchar2(100 byte),

pid   number                                  default 0

insert into tbl_test(id,name,pid) values('1','10','0');

insert into tbl_test(id,name,pid) values('2','11','1'

insert into tbl_test(id,name,pid) values('3','20','0');

insert into tbl_test(id,name,pid) values('4','12','1');

insert into tbl_test(id,name,pid) values('5','121','2');

二、格式

select * from …. where [結果過濾條件語句]

start with  [and起始條件過濾語句]

connect by prior [and中間記錄過濾條件語句]

三、查詢所有下級

select * from tbl_test start with id=1 connect by prior id=pid

注意:此sql能查詢id=1的資料的所有下級,寫sql語句時要注意,因為是從id開始查詢下級,所以connect by prior 子句的條件是id=pid

四、查詢所有上級

select * from tbl_test start with id=5 connect by prior pid=id

因為是從id開始查詢上級,所以connect by prior 子句的條件是pid=d

db2 遞迴方式:

遞迴 sql 在 

db2 中通過公共表表示式 (cte,common table expression) 來實現。遞迴 sql 由遞迴 cte 以及對遞迴 cte 結果的查詢組成。那什麼是遞迴 cte 呢?簡言之,如果 cte 中的 fullselect 在 from 子句中引用到 cte 本身,就是遞迴 cte。遞迴 cte 包含以下三個組成部分:

下面我們用乙個簡單的例子來說明初始查詢,遞迴查詢和終止條件是如何實現乙個遞迴 cte 的。

工作原理

以下通過乙個描述節點層次關係的例項來說明遞迴 sql 的工作原理。

首先執行清單 1 中的 sql 語句來建立該例項所用的表和資料。

清單 1. 建立 node 表和資料

create table node( child integer not null, parent integer not null); insert into node values(1, 0); insert into node values(2, 6); insert into node values(3, 1); insert into node values(4, 5); insert into node values(5, 3); insert into node values(6, 3); insert into node values(7, 5); insert into node values(8, 5);

成功執行清單 1 中的 sql 後,node 表的內容如表 1 所示。

表 1. node 表

childparent10

2631

4553

6375

85

則清單 2 中的 sql 將得出 node 表的層次結構。

清單 2. node 表層次結構查詢

with report(parent, child) as ( select parent, child from node where parent = 0 union all select b.parent, b.child from report a, node b where b.parent = a.child ) select * from report;

詳見:

DB2 遞迴SQL寫法

with temptab pro komcode,pro komcode o,pro sup code as select root.pro komcode,root.pro komcode o,root.pro sup code from product root where pro komcod...

遞迴的寫法

foreach datarow dr0 in dt.rows tn1 new treenode tn1.nodes.add tn0 tn1 tn0 tn3 tn1 method tn1 treeview1.nodes.add tn1 private void method treenode tn1 ...

遞迴寫法總結

遞迴是演算法中的一種很重要思想。好的遞迴程式邏輯清楚,簡潔,有時候時間上也非常高效 此外鍊錶 二叉樹等結構用遞迴演算法一般都有鮮明優勢。往往遞迴問題口頭說起來感覺十分清晰順暢 而用 實現起來確總感覺層巒疊嶂,不知從何下手,思路也越來越混亂不堪。最近在解決一些演算法相關的小問題時候,經常需要用到遞迴,...