[MySQL] 实现树形的遍历(关于多级菜单栏以及多级上下部门的查询问题)
前言:
关于多级别菜单栏或者权限系统中部门上下级的树形遍历,oracle中有connect by来实现,mysql没有这样的便捷途径,所以MySQL遍历数据表是我们经常会遇到的头痛问题,下面通过存储过程来实现。
1,建立测试表和数据:
DROP TABLE IF EXISTS csdn.channel;
CREATE TABLE csdn.channel (
id INT(11) NOT NULL AUTO_INCREMENT,
cname VARCHAR(200) DEFAULT NULL,
parent_id INT(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=INNODB DEFAULT CHARSET=utf8;
INSERT INTO channel(id,cname,parent_id)
VALUES (13,'首页',-1),
(14,'TV580',-1),
(15,'生活580',-1),
(16,'左上幻灯片',13),
(17,'帮忙',14),
(18,'栏目简介',17);
DROP TABLE IF EXISTS channel;
2,利用临时表和递归过程实现树的遍历(mysql的UDF不能递归调用):
2.1,从某节点向下遍历子节点,递归生成临时表数据
-- pro_cre_childlist
DELIMITER $$
DROP PROCEDURE IF EXISTS csdn.pro_cre_childlist$$
CREATE PROCEDURE csdn.pro_cre_childlist(IN rootId INT,IN nDepth INT)
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE b INT;
DECLARE cur1 CURSOR FOR SELECT id FROM channel WHERE parent_id=rootId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
SET max_sp_recursion_depth=12;
INSERT INTO tmpLst VALUES (NULL,rootId,nDepth);
OPEN cur1;
FETCH cur1 INTO b;
WHILE done=0 DO
CALL pro_cre_childlist(b,nDepth+1);
FETCH cur1 INTO b;
END WHILE;
CLOSE cur1;
END$$
2.2,从某节点向上追溯根节点,递归生成临时表数据
-- pro_cre_parentlist
DELIMITER $$
DROP PROCEDURE IF EXISTS csdn.pro_cre_parentlist$$
CREATE PROCEDURE csdn.pro_cre_parentlist(IN rootId INT,IN nDepth INT)
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE b INT;
DECLARE cur1 CURSOR FOR SELECT parent_id FROM channel WHERE id=rootId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
SET max_sp_recursion_depth=12;
INSERT INTO tmpLst VALUES (NULL,rootId,nDepth);
OPEN cur1;
FETCH cur1 INTO b;
WHILE done=0 DO
CALL pro_cre_parentlist(b,nDepth+1);
FETCH cur1 INTO b;
END WHILE;
CLOSE cur1;
END$$
2.3,实现类似Oracle SYS_CONNECT_BY_PATH的功能,递归过程输出某节点id路径
-- pro_cre_pathlist
DELIMITER $$
USE csdn$$
DROP PROCEDURE IF EXISTS pro_cre_pathlist$$
CREATE PROCEDURE pro_cre_pathlist(IN nid INT,IN delimit VARCHAR(10),INOUT pathstr VARCHAR(1000))
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE parentid INT DEFAULT 0;
DECLARE cur1 CURSOR FOR
SELECT t.parent_id,CONCAT(CAST(t.parent_id AS CHAR),delimit,pathstr)
FROM channel AS t WHERE t.id = nid;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
SET max_sp_recursion_depth=12;
OPEN cur1;
FETCH cur1 INTO parentid,pathstr;
WHILE done=0 DO
CALL pro_cre_pathlist(parentid,delimit,pathstr);
FETCH cur1 INTO parentid,pathstr;
END WHILE;
CLOSE cur1;
END$$
DELIMITER ;
2.4,递归过程输出某节点name路径
-- pro_cre_pnlist
DELIMITER $$
USE csdn$$
DROP PROCEDURE IF EXISTS pro_cre_pnlist$$
CREATE PROCEDURE pro_cre_pnlist(IN nid INT,IN delimit VARCHAR(10),INOUT pathstr VARCHAR(1000))
BEGIN
DECLARE done INT DEFAULT 0;
DECLARE parentid INT DEFAULT 0;
DECLARE cur1 CURSOR FOR
SELECT t.parent_id,CONCAT(t.cname,delimit,pathstr)
FROM channel AS t WHERE t.id = nid;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1;
SET max_sp_recursion_depth=12;
OPEN cur1;
FETCH cur1 INTO parentid,pathstr;
WHILE done=0 DO
CALL pro_cre_pnlist(parentid,delimit,pathstr);
FETCH cur1 INTO parentid,pathstr;
END WHILE;
CLOSE cur1;
END$$
DELIMITER ;
2.5,调用函数输出id路径
-- fn_tree_path
DELIMITER $$
DROP FUNCTION IF EXISTS csdn.fn_tree_path$$
CREATE FUNCTION csdn.fn_tree_path(nid INT,delimit VARCHAR(10)) RETURNS VARCHAR(2000) CHARSET utf8
BEGIN
DECLARE pathid VARCHAR(1000);
SET @pathid=CAST(nid AS CHAR);
CALL pro_cre_pathlist(nid,delimit,@pathid);
RETURN @pathid;
END$$
2.6,调用函数输出name路径
-- fn_tree_pathname
-- 调用函数输出name路径
DELIMITER $$
DROP FUNCTION IF EXISTS csdn.fn_tree_pathname$$
CREATE FUNCTION csdn.fn_tree_pathname(nid INT,delimit VARCHAR(10)) RETURNS VARCHAR(2000) CHARSET utf8
BEGIN
DECLARE pathid VARCHAR(1000);
SET @pathid='';
CALL pro_cre_pnlist(nid,delimit,@pathid);
RETURN @pathid;
END$$
DELIMITER ;
2.7,调用过程输出子节点
-- pro_show_childLst
DELIMITER $$
-- 调用过程输出子节点
DROP PROCEDURE IF EXISTS pro_show_childLst$$
CREATE PROCEDURE pro_show_childLst(IN rootId INT)
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmpLst;
CREATE TEMPORARY TABLE IF NOT EXISTS tmpLst
(sno INT PRIMARY KEY AUTO_INCREMENT,id INT,depth INT);
CALL pro_cre_childlist(rootId,0);
SELECT channel.id,CONCAT(SPACE(tmpLst.depth*2),'--',channel.cname) NAME,channel.parent_id,tmpLst.depth,fn_tree_path(channel.id,'/') path,fn_tree_pathname(channel.id,'/') pathname
FROM tmpLst,channel WHERE tmpLst.id=channel.id ORDER BY tmpLst.sno;
END$$
2.8,调用过程输出父节点
-- pro_show_parentLst
DELIMITER $$
-- 调用过程输出父节点
DROP PROCEDURE IF EXISTS `pro_show_parentLst`$$
CREATE PROCEDURE `pro_show_parentLst`(IN rootId INT)
BEGIN
DROP TEMPORARY TABLE IF EXISTS tmpLst;
CREATE TEMPORARY TABLE IF NOT EXISTS tmpLst
(sno INT PRIMARY KEY AUTO_INCREMENT,id INT,depth INT);
CALL pro_cre_parentlist(rootId,0);
SELECT channel.id,CONCAT(SPACE(tmpLst.depth*2),'--',channel.cname) NAME,channel.parent_id,tmpLst.depth,fn_tree_path(channel.id,'/') path,fn_tree_pathname(channel.id,'/') pathname
FROM tmpLst,channel WHERE tmpLst.id=channel.id ORDER BY tmpLst.sno;
END$$
3,开始测试:
3.1,从根节点开始显示,显示子节点集合:
mysql> CALL pro_show_childLst(-1);
+----+-----------------------+-----------+-------+-------------+----------------------------+
| id | NAME | parent_id | depth | path | pathname |
+----+-----------------------+-----------+-------+-------------+----------------------------+
| 13 | --首页 | -1 | 1 | -1/13 | 首页/ |
| 16 | --左上幻灯片 | 13 | 2 | -1/13/16 | 首页/左上幻灯片/ |
| 14 | --TV580 | -1 | 1 | -1/14 | TV580/ |
| 17 | --帮忙 | 14 | 2 | -1/14/17 | TV580/帮忙/ |
| 18 | --栏目简介 | 17 | 3 | -1/14/17/18 | TV580/帮忙/栏目简介/ |
| 15 | --生活580 | -1 | 1 | -1/15 | 生活580/ |
+----+-----------------------+-----------+-------+-------------+----------------------------+
6 rows in set (0.05 sec)
Query OK, 0 rows affected (0.05 sec)
3.2,显示首页下面的子节点
CALL pro_show_childLst(13);
mysql> CALL pro_show_childLst(13);
+----+---------------------+-----------+-------+----------+-------------------------+
| id | NAME | parent_id | depth | path | pathname |
+----+---------------------+-----------+-------+----------+-------------------------+
| 13 | --首页 | -1 | 0 | -1/13 | 首页/ |
| 16 | --左上幻灯片 | 13 | 1 | -1/13/16 | 首页/左上幻灯片/ |
+----+---------------------+-----------+-------+----------+-------------------------+
2 rows in set (0.02 sec)
Query OK, 0 rows affected (0.02 sec)
mysql>
3.3,显示TV580下面的所有子节点
CALL pro_show_childLst(14);
mysql> CALL pro_show_childLst(14);
+----+--------------------+-----------+-------+-------------+----------------------------+
| id | NAME | parent_id | depth | path | pathname |
+----+--------------------+-----------+-------+-------------+----------------------------+
| 14 | --TV580 | -1 | 0 | -1/14 | TV580/ |
| 17 | --帮忙 | 14 | 1 | -1/14/17 | TV580/帮忙/ |
| 18 | --栏目简介 | 17 | 2 | -1/14/17/18 | TV580/帮忙/栏目简介/ |
+----+--------------------+-----------+-------+-------------+----------------------------+
3 rows in set (0.02 sec)
Query OK, 0 rows affected (0.02 sec)
mysql>
3.4,“帮忙”节点有一个子节点,显示出来:
CALL pro_show_childLst(17);
mysql> CALL pro_show_childLst(17);
+----+------------------+-----------+-------+-------------+----------------------------+
| id | NAME | parent_id | depth | path | pathname |
+----+------------------+-----------+-------+-------------+----------------------------+
| 17 | --帮忙 | 14 | 0 | -1/14/17 | TV580/帮忙/ |
| 18 | --栏目简介 | 17 | 1 | -1/14/17/18 | TV580/帮忙/栏目简介/ |
+----+------------------+-----------+-------+-------------+----------------------------+
2 rows in set (0.03 sec)
Query OK, 0 rows affected (0.03 sec)
mysql>
3.5,“栏目简介”没有子节点,所以只显示最终节点:
mysql> CALL pro_show_childLst(18);
+----+----------------+-----------+-------+-------------+----------------------------+
| id | NAME | parent_id | depth | path | pathname |
+----+----------------+-----------+-------+-------------+----------------------------+
| 18 | --栏目简介 | 17 | 0 | -1/14/17/18 | TV580/帮忙/栏目简介/ |
+----+----------------+-----------+-------+-------------+----------------------------+
1 row in set (0.36 sec)
Query OK, 0 rows affected (0.36 sec)
mysql>
3.6,显示根节点的父节点
CALL pro_show_parentLst(-1);
mysql> CALL pro_show_parentLst(-1);
Empty set (0.01 sec)
Query OK, 0 rows affected (0.01 sec)
mysql>
3.7,显示“首页”的父节点
CALL pro_show_parentLst(13);
mysql> CALL pro_show_parentLst(13);
+----+----------+-----------+-------+-------+----------+
| id | NAME | parent_id | depth | path | pathname |
+----+----------+-----------+-------+-------+----------+
| 13 | --首页 | -1 | 0 | -1/13 | 首页/ |
+----+----------+-----------+-------+-------+----------+
1 row in set (0.02 sec)
Query OK, 0 rows affected (0.02 sec)
mysql>
3.8,显示“TV580”的父节点,parent_id为-1
CALL pro_show_parentLst(14);
mysql> CALL pro_show_parentLst(14);
+----+---------+-----------+-------+-------+----------+
| id | NAME | parent_id | depth | path | pathname |
+----+---------+-----------+-------+-------+----------+
| 14 | --TV580 | -1 | 0 | -1/14 | TV580/ |
+----+---------+-----------+-------+-------+----------+
1 row in set (0.02 sec)
Query OK, 0 rows affected (0.02 sec)
3.9,显示“帮忙”节点的父节点
mysql>
CALL pro_show_parentLst(17);
mysql> CALL pro_show_parentLst(17);
+----+-----------+-----------+-------+----------+---------------+
| id | NAME | parent_id | depth | path | pathname |
+----+-----------+-----------+-------+----------+---------------+
| 17 | --帮忙 | 14 | 0 | -1/14/17 | TV580/帮忙/ |
| 14 | --TV580 | -1 | 1 | -1/14 | TV580/ |
+----+-----------+-----------+-------+----------+---------------+
2 rows in set (0.02 sec)
Query OK, 0 rows affected (0.02 sec)
mysql>
3.10,显示最低层节点“栏目简介”的父节点
CALL pro_show_parentLst(18);
mysql> CALL pro_show_parentLst(18);
+----+----------------+-----------+-------+-------------+----------------------------+
| id | NAME | parent_id | depth | path | pathname |
+----+----------------+-----------+-------+-------------+----------------------------+
| 18 | --栏目简介 | 17 | 0 | -1/14/17/18 | TV580/帮忙/栏目简介/ |
| 17 | --帮忙 | 14 | 1 | -1/14/17 | TV580/帮忙/ |
| 14 | --TV580 | -1 | 2 | -1/14 | TV580/ |
+----+----------------+-----------+-------+-------------+----------------------------+
3 rows in set (0.02 sec)
Query OK, 0 rows affected (0.02 sec)
mysql>
转自: http://blog.itpub.net/26230597/viewspace-1269668/
在Oracle 中我们知道有一个 Hierarchical Queries 通过CONNECT BY 我们可以方便的查了所有当前节点下的所有子节点。但很遗憾,在MySQL的目前版本中还没有对应的功能。
在MySQL中如果是有限的层次,比如我们事先如果可以确定这个树的最大深度是4, 那么所有节点为根的树的深度均不会超过4,则我们可以直接通过left join 来实现。
但很多时候我们无法控制树的深度。这时就需要在MySQL中用存储过程来实现或在你的程序中来实现这个递归。本文讨论一下几种实现的方法。
样例数据:
mysql> create table treeNodes -> ( -> id int primary key, -> nodename varchar(20), -> pid int -> ); Query OK, 0 rows affected (0.09 sec) mysql> 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, 得到一个由所有子节点号组成的字符串.
mysql> delimiter // mysql> mysql> 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; -> END -> // Query OK, 0 rows affected (0.00 sec)
mysql> mysql> delimiter ;
使用我们直接利用find_in_set函数配合这个getChildlst来查找
mysql> select getChildLst(1); +-----------------+ | getChildLst(1) | +-----------------+ | $,1,2,3,4,5,6,7 | +-----------------+ 1 row in set (0.00 sec)
mysql> 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 | +----+----------+------+ 7 rows in set (0.01 sec)
mysql> select * from treeNodes -> where FIND_IN_SET(id, getChildLst(3)); +----+----------+------+ | id | nodename | pid | +----+----------+------+ | 3 | C | 1 | | 6 | F | 3 | | 7 | G | 6 | +----+----------+------+ 3 rows in set (0.01 sec)
优点: 简单,方便,没有递归调用层次深度的限制 (max_sp_recursion_depth,最大255) ;
缺点:长度受限,虽然可以扩大 RETURNS varchar(1000),但总是有最大限制的。
MySQL目前版本( 5.1.33-community)中还不支持function 的递归调用。
方法二:利用临时表和过程递归
创建存储过程如下。createChildLst 为递归过程,showChildLst为调用入口过程,准备临时表及初始化。
mysql> delimiter // mysql> mysql> # 入口过程 mysql> CREATE PROCEDURE showChildLst (IN rootId INT) -> BEGIN -> CREATE TEMPORARY TABLE IF NOT EXISTS tmpLst -> (sno int primary key auto_increment,id int,depth int); -> DELETE FROM tmpLst; -> -> CALL createChildLst(rootId,0); -> -> select tmpLst.*,treeNodes.* from tmpLst,treeNodes where tmpLst.id=treeNodes.id order by tmpLst.sno; -> END; -> // Query OK, 0 rows affected (0.00 sec)
mysql> mysql> # 递归过程 mysql> CREATE PROCEDURE createChildLst (IN rootId INT,IN nDepth INT) -> BEGIN -> DECLARE done INT DEFAULT 0; -> DECLARE b INT; -> DECLARE cur1 CURSOR FOR SELECT id FROM treeNodes where pid=rootId; -> DECLARE CONTINUE HANDLER FOR NOT FOUND SET done = 1; -> -> insert into tmpLst values (null,rootId,nDepth);
-> -> OPEN cur1; -> -> FETCH cur1 INTO b; -> WHILE done=0 DO -> CALL createChildLst(b,nDepth+1); -> FETCH cur1 INTO b; -> END WHILE; -> -> CLOSE cur1; -> END; -> // Query OK, 0 rows affected (0.00 sec) mysql> delimiter ;
调用时传入结点
mysql> call showChildLst(1); +-----+------+-------+----+----------+------+ | sno | id | depth | id | nodename | pid | +-----+------+-------+----+----------+------+ | 4 | 1 | 0 | 1 | A | 0 | | 5 | 2 | 1 | 2 | B | 1 | | 6 | 4 | 2 | 4 | D | 2 | | 7 | 5 | 2 | 5 | E | 2 | | 8 | 3 | 1 | 3 | C | 1 | | 9 | 6 | 2 | 6 | F | 3 | | 10 | 7 | 3 | 7 | G | 6 | +-----+------+-------+----+----------+------+
7 rows in set (0.13 sec)
Query OK, 0 rows affected, 1 warning (0.14 sec)
mysql> mysql> call showChildLst(3); +-----+------+-------+----+----------+------+ | sno | id | depth | id | nodename | pid | +-----+------+-------+----+----------+------+ | 1 | 3 | 0 | 3 | C | 1 | | 2 | 6 | 1 | 6 | F | 3 | | 3 | 7 | 2 | 7 | G | 6 | +-----+------+-------+----+----------+------+
3 rows in set (0.11 sec)
Query OK, 0 rows affected, 1 warning (0.11 sec)
depth 为深度,这样可以在程序进行一些显示上的格式化处理。类似于oracle中的 level 伪列。sno 仅供排序控制。这样你还可以通过临时表tmpLst与数据库中其它表进行联接查询。
MySQL中你可以利用系统参数 max_sp_recursion_depth 来控制递归调用的层数上限。如下例设为12.
mysql> set max_sp_recursion_depth=12; Query OK, 0 rows affected (0.00 sec)
优点 : 可以更灵活处理,及层数的显示。并且可以按照树的遍历顺序得到结果。
缺点 : 递归有255的限制。
方法三:利用中间表和过程
(本方法由yongyupost2000提供样子改编)
创建存储过程如下。由于MySQL中不允许在同一语句中对临时表多次引用,只以使用普通表tmpLst来实现了。当然你的程序中负责在用完后清除这个表。
delimiter //
drop PROCEDURE IF EXISTS showTreeNodes_yongyupost2000//
CREATE PROCEDURE showTreeNodes_yongyupost2000 (IN rootid INT) BEGIN DECLARE Level int ; drop TABLE IF EXISTS tmpLst; CREATE TABLE tmpLst ( id int, nLevel int, sCort varchar(8000) ); Set Level=0 ; INSERT into tmpLst SELECT id,Level,ID FROM treeNodes WHERE PID=rootid; WHILE ROW_COUNT()>0 DO SET Level=Level+1 ; INSERT into tmpLst SELECT A.ID,Level,concat(B.sCort,A.ID) FROM treeNodes A,tmpLst B WHERE A.PID=B.ID AND B.nLevel=Level-1 ; END WHILE; END; //
delimiter ;
CALL showTreeNodes_yongyupost2000(0);
执行完后会产生一个tmpLst表,nLevel 为节点深度,sCort 为排序字段。 使用方法
SELECT concat(SPACE(B.nLevel*2),'+--',A.nodename) FROM treeNodes A,tmpLst B WHERE A.ID=B.ID ORDER BY B.sCort;
+--------------------------------------------+ | concat(SPACE(B.nLevel*2),'+--',A.nodename) | +--------------------------------------------+ | +--A | | +--B | | +--D | | +--E | | +--C | | +--F | | +--G | | +--H | | +--J | | +--K | | +--I | | +--L | | +--N | | +--O | | +--P | | +--Q | | +--M | +--------------------------------------------+ 17 rows in set (0.00 sec)