mysql遞迴查詢函式

2021-10-11 04:38:11 字數 2669 閱讀 2744

-- 獲取祖先區劃列表

create

definer

=`root`

@`%`

function

`getparentlist`

(`rootid`

varchar

(10000))

returns

varchar

(10000

)charset utf8

deterministic

begin

declare sparentlist varchar

(10000);

-- 父區劃集(上面所有層的父區劃合集)

declare sparenttemp varchar

(10000);

-- 區劃快取

-- 查出上一層層父區劃賦值給區劃快取

select group_concat(parentid)

into sparenttemp from t_sys_region where areaid = rootid;

-- 如果區劃快取不為空

while sparenttemp is

notnull

do-- 為父區劃集賦值(如果父區劃集不為空則在前面加上區劃快取,否則賦值區劃快取)

if(sparentlist is

notnull

)then

set sparentlist = concat(sparenttemp,

',',sparentlist)

;else

set sparentlist = sparenttemp;

endif

;-- 在當前n層父區劃的基礎上查出上n+1層的父區劃賦值給區劃快取

select group_concat(parentid)

into sparenttemp from t_sys_region where find_in_set(areaid,sparenttemp)

>0;

endwhile

;return sparentlist;

end

-- 獲取所有後代區劃列表

create

definer

=`root`

@`%`

function

`getchildrelist`

(`rootid`

varchar

(10000))

returns

varchar

(10000

)charset utf8

deterministic

begin

declare schildrenlist varchar

(10000);

-- 子區劃集(下面所有層的子區劃合集)

declare schildrentemp varchar

(10000);

-- 區劃快取

-- 查出下一層子區劃賦值區劃快取

select group_concat(areaid)

into schildrentemp from t_sys_region where parentid = rootid;

-- 如果區劃快取不為空

while schildrentemp is

notnull

do-- 為子區劃集賦值(如果子區劃集不為空則在前面加上區劃快取,否則賦值區劃快取)

if(schildrenlist is

notnull

)then

set schildrenlist = concat(schildrentemp,

',', schildrenlist)

;else

set schildrenlist = concat(schildrentemp)

;endif;

-- 在當前n層子區劃的基礎上查出下n+1層的子區劃賦值給區劃快取

select group_concat(areaid)

into schildrentemp from t_sys_region where find_in_set(parentid, schildrentemp)

>0;

endwhile

;return schildrenlist;

end

-- 查出上線下樹區劃列表

create

definer

=`root`

@`%`

function

`getareaids`

(`rootid`

varchar

(10000))

returns

varchar

(10000

)charset utf8

deterministic

begin

declare areaids varchar

(10000);

select concat_ws(

',',getparentlist(rootid)

,rootid,getchildrelist(rootid)

)into areaids;

return areaids;

end

mysql 遞迴 mysql遞迴查詢

find in set 函式 函式語法 find in set str,strlist str 代表要查詢的字串 strlist 是乙個以逗號分隔的字串,如 a,b,c 此函式用於查詢 str 字串在字串 strlist 中的位置,返回結果為 1 n 若沒有找到,則返回0。concat 它用於連線n...

mysql遞迴查詢統計 mysql遞迴查詢

樣例資料 create table treenodes id int primary key,nodename varchar 20 pid int select from treenodes id nodename pid 1 a 0 2 b 1 3 c 1 4 d 2 5 e 2 6 f 3 7...

mysql 遞迴查詢效率 mysql 遞迴查詢

set stemp set stempchd cast id as char 轉化資料格式 while stempchd is not null do 開始迴圈 set stemp concat stemp,stempchd 字串拼接 select group concat id into stem...