父節點遞迴查詢和子節點遞迴查詢函式

2021-09-07 18:24:35 字數 2126 閱讀 8282

由於在專案中用到了向上查詢父節點的遞迴查詢和向下查詢子節點查詢的遞迴查詢,由於在實現過程中,寫遞迴查詢的sql函式

花費了較長的時間,所以在此總結一下,兩種遞迴查詢的函式的實現寫法:

向下查詢子節點的遞迴查詢:

先展示表結構:

根據區域查詢對應的下級區域資訊,其中parentid為zoneid對應的下級區域id資訊。當再查詢下級區域資訊時,即可將parentid作為zoneid來

查詢子節點資訊,由於不同區域對應的子節點層數也不一樣,當要獲取所有子節點的zoneid時,可以使用以下的遞迴查詢:

begin

declare stemp varchar(

10000

); declare stempchd varchar(

10000

); set stemp = '$'

; set stempchd =cast(rootid as char);

while stempchd is not null do

set stemp = concat(stemp, ','

, stempchd);

select group_concat(zoneid) into stempchd from tbl_zone_info where status!='

3' and find_in_set(parentid,stempchd)>0

; end while;

return stemp;

end

使用方式:

向上查詢的父查詢遞迴查詢:

先展示表結構:

根據組id查詢對應的父組有哪些:parentid即為對應groupid組id的父組id,當獲取到父組id即parentid,即可以將parentid作為groupid組id

查詢到父組的資訊。

實現的遞迴函式為:

begin   

declare fid varchar(100) default '';

declare str varchar(1000) default

rootid;

while rootid is not

null

doset fid =(select parentid from tbl_group_info where groupid =rootid);

if fid is not

null

then

set str = concat(str, ',', fid);

set rootid =fid;

else

set rootid =fid;

end if;

end while;

return

str;

end

使用方式:

當得知層級關係時,可以直接使用以下sql,進行自我聯查:

select  a.groupname as lev1,b.groupname as lev2,c.groupname as lev3,d.groupname as lev4 from tbl_group_info a

left join tbl_group_info b on a.parentid  = b.groupid

left join tbl_group_info c on b.parentid  = c.groupid

left join tbl_group_info d on c.parentid  = d.groupid

where a.groupid = '320100201712010942533991024gleax'

根據子節點遞迴查詢所有父節點

有個需求,需要根據給定的子節點向上遞迴查詢所有父節點,網上查詢了一些,但是都不是很滿意,有的是需要用到全域性變數定義儲存列表,但是會有併發問題,然後自己手寫乙個 test void contextloads1 public listgetpid listidlist,integer pid,list...

oracle遞迴查詢子節點

通過子節點向根節點追朔.select from persons.dept start with deptid 76 connect by prior paredeptid deptid 通過根節點遍歷子節點 不包含根節點 select from persons.dept start with par...

Mysql 遞迴查詢子節點

查詢父編碼及以下所有子節點 select id from select t1.id,t1.parent id,if find in set t1.id,pids 0,pids,if find in set t1.parent id,pids 0,pids concat ws pids,id 0 as...