表结构数据如下:
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的所有下级。
结果截图: