mysql 實現遞迴查詢

2021-10-25 08:01:56 字數 998 閱讀 1040

遞迴查詢父類的所有子節點

select * from (

select t1.*,

if(find_in_set(parentid, @pids) > 0, @pids := concat(@pids, ',', id), 0) as ischild

from (

select * from tbl_dept t where t.status = 0 order by parentid, id

) t1,

(select @pids := 2) t2

) t3 where ischild != 0

查詢結果不包含自己,若想包含自己,將if(find_in_set(parentid, @pids) > 0, @pids := concat(@pids, 『,』, id), 0) as ischild修改為if(find_in_set(parentid, @pids) > 0 || id=@pids, @pids := concat(@pids, 『,』, id), 0) as ischild即可

hibernate 報錯 space is not allowed after parameter prefix 『:』

解決方式:

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

select id,name,level,parentid

from (

select

@r as _id,

(select @r := parentid from tbl_dept where id = _id) as parent_id,

@l := @l + 1 as lvl

from

(select @r := 8, @l := 0) vars,

tbl_dept h

where @r <> 0) t1

join tbl_dept t2

on t1._id = t2.id

order by id

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