資料庫實現遞迴查詢,獲取節點的所有子孫節點

2021-10-11 21:19:56 字數 893 閱讀 5141

with cte as

(select orgid from fx_org where orgid =

'138'

union all

select fx_org.orgid from fx_org inner join cte on fx_org.parentid = cte.orgid )

select * from cte

這個地方使用的sqlserver的遞迴寫法,如果使用的資料庫是mysql的話,就需要下面的一種寫法:

with recursive cte as

(select orgid from fx_org where orgid =

'2'union all

select fx_org.orgid from fx_org inner join cte on fx_org.parentid = cte.orgid )

select * from cte;

其他的地方沒有什麼區別,只需要加乙個recursive。

如果需要巢狀在另外的乙個sql語句中:

with cte as

(select orgid from fx_org where orgid =

'138'

union all

select fx_org.orgid from fx_org inner join cte on fx_org.parentid = cte.orgid )

select count(*) from cte inner join zw_zmhd on cte.orgid=zw_zmhd.bm where hdlx =

'1'

這裡的cte就像是乙個新的**

C 實現資料庫的遞迴查詢

表結構如下 標識號 名稱 上級標識號 mid mname mparentid 1 選單一 0 2 選單二 1 3 選單三 1 4 選單四 2 5 選單五 3 要用遞迴程式實現某一標識號 包括本身 下的所有選單,要實現這個程式,我們這裡取出所有符合的選單標識號,用 連線成字串,實現的方法如下 取得選單...

資料庫遞迴查詢

今天工作看同事 用到了start with.connect by prior,不知道什麼意思,查詢了一些資料,以下是比較好理解的。oracle中的select語句可以用start with.connect by prior子句實現遞迴查詢,connect by 是結構化查詢中用到的,其基本語法是 s...

如何使用資料庫實現遞迴查詢

sql server 2005開始,我們可以直接通過cte來支援遞迴查詢,cte即公用表表示式 公用表表示式 cte 是乙個在查詢中定義的臨時命名結果集將在from子句中使用它。每個cte僅被定義一次 但在其作用域內可以被引用任意次 並且在該查詢生存期間將一直生存。可以使用cte來執行遞迴操作。建立...