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

2021-10-18 06:02:26 字數 2055 閱讀 6860

樣例資料:

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 | g | 6 |

| 8 | h | 0 |

| 9 | i | 8 |

| 10 | j | 8 |

| 11 | k | 8 |

| 12 | l | 9 |

| 13 | m | 9 |

| 14 | n | 12 |

| 15 | o | 12 |

| 16 | p | 15 |

| 17 | q | 15 |

17 rows in set (0.00 sec)

樹形圖如下

1:a+-- 2:b

| +-- 4:d

| +-- 5:e

+-- 3:c

+-- 6:f

+-- 7:g

8:h+-- 9:i

| +-- 12:l

| | +--14:n

| | +--15:o

| | +--16:p

| | +--17:q

| +-- 13:m

+-- 10:j

+-- 11:k

建立乙個function getchildlst, 得到乙個由所有子節點號組成的字串.

delimiter //

create function `getchildlst`(rootid int)

returns varchar(1000)

begin

declare stemp varchar(1000);

declare stempchd varchar(1000);

set stemp = 『$『;

set stempchd =cast(rootid as char);

while stempchd is not null do

set stemp = concat(stemp,『,『,stempchd);

select group_concat(id) into stempchd from treenodes where find_in_set(pid,stempchd)>0;

end while;

return stemp;

enddelimiter ;

使用我們直接利用find_in_set函式配合這個getchildlst來查詢

select getchildlst(1);

| getchildlst(1) |

| $,1,2,3,4,5,6,7 |

select * from treenodes where find_in_set(id, getchildlst(1));

| id | nodename | pid |

| 1 | a | 0 |

| 2 | b | 1 |

| 3 | c | 1 |

| 4 | d | 2 |

| 5 | e | 2 |

| 6 | f | 3 |

| 7 | g | 6 |

select * from treenodes where find_in_set(id, getchildlst(3));

| id | nodename | pid |

| 3 | c | 1 |

| 6 | f | 3 |

| 7 | g | 6 |

優點:簡單,方便,沒有遞迴呼叫層次深度的限制 (max_sp_recursion_depth,最大255);

缺點:長度受限,雖然可以擴大 returns varchar(1000),但總是有最大限制的。

MySQ樹狀結構資料 遞迴查詢

for example create table products id int,name varchar 100 parent id int insert into products values 15,category15 0 not a descendant of 19 16,category...

mysql 遞迴 mysql遞迴查詢

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

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...