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

2021-10-20 22:37:15 字數 973 閱讀 2019

set stemp=『$『;

set stempchd = cast(id as char); -- 轉化資料格式

while stempchd is not null do  -- 開始迴圈

set stemp= concat(stemp,『,『,stempchd); -- 字串拼接

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

-- group_concat()會計算哪些行屬於同一組,並且將同一組的 引數 拼接成字串 以逗號形式隔開;

-- find_in_set(pid,stempchd) 判斷 pid 是否在 stempchd 中

-- 該語句的意思是 查詢 user 表,所查詢的資料的 pid 在 stempchd 中,並且將查到的 id 形成乙個由 逗號 隔開的字串,重新賦值給 stempchd ;當 stempchd 有值,再次迴圈,沒有值,跳出迴圈,

-- 迴圈中將查到的資料拼成了 stemp 字串

end while;

-- 對 stemp  處理

select length(stemp)-length(replace(stemp,『,『,『『)) into invitorn;

set invitorn = invitorn + 1;

while j <= invitorn do

select substring_index(stemp, 『,『, j) into tempstr;

select substring(tempstr,m+1) into tempuserid;

set m = length(tempstr) + 1;

set j = j +1 ;

if tempuserid != userid then

***x

end if;

end while;

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遞迴查詢

樣例資料 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...