表結構資料如下:
id:主鍵id
nodename:節點名稱(部門名稱)
pid:父id
description:描述資訊
如果是oracle資料庫:
select *
from dept t
connect by prior t.pid = t.id
start with t.id = 1;
如果是mysql資料庫:
select id as id,nodename 節點描述 ,pid as 父id , description as 描述,levels as 父到子之間級數, paths as 父到子路徑 from (
select id,pid,nodename,description,
@le:= if (pid = 0 ,0,
if( locate( concat('|',pid,':'),@pathlevel) > 0 ,
substring_index( substring_index(@pathlevel,concat('|',pid,':'),-1),'|',1) +1
,@le+1) ) levels
, @pathlevel:= concat(@pathlevel,'|',id,':', @le ,'|') pathlevel
, @pathnodes:= if( pid =0,',0',
concat_ws(',',
if( locate( concat('|',pid,':'),@pathall) > 0 ,
substring_index( substring_index(@pathall,concat('|',pid,':'),-1),'|',1)
,@pathnodes ) ,pid ) )paths
,@pathall:=concat(@pathall,'|',id,':', @pathnodes ,'|') pathall
from dept,
(select @le:=0,@pathlevel:='', @pathall:='',@pathnodes:='') vv
order by pid,id
) src
order by id
結果截圖:
如果是查詢所有下級:
select id,pid,nodename,description from
(select
id,pid
,@le:= if (pid = 0 ,0,if( locate( concat('|',pid,':'),@pathlevel) > 0 ,substring_index( substring_index(@pathlevel,concat('|',pid,':'),-1),'|',1) +1,@le+1) ) levels
,@pathlevel:= concat(@pathlevel,'|',id,':', @le ,'|') pathlevel
,@pathnodes:= if( pid =0,',0',concat_ws(',',if( locate( concat('|',pid,':'),@pathall) > 0 , substring_index( substring_index(@pathall,concat('|',pid,':'),-1),'|',1),@pathnodes ) ,pid ) )paths
,@pathall:=concat(@pathall,'|',id,':', @pathnodes ,'|') pathall
,nodename
,description
from dept,
(select @le:=0,@pathlevel:='', @pathall:='',@pathnodes:='') vv
order by pid,id
) src
where locate(',2',paths) > 0 order by id
其中 最後",2"為要查詢的引數id,就是查詢 id =2的所有下級。
結果截圖:
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...