Home Database Mysql Tutorial 实现树形的遍历(关于多级菜单栏以及多级上下部门的查询问题)_MySQL

实现树形的遍历(关于多级菜单栏以及多级上下部门的查询问题)_MySQL

May 30, 2016 pm 05:11 PM
up and down menu

前言:

        关于多级别菜单栏或者权限系统中部门上下级的树形遍历,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;
Copy after login

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$$   
Copy after login

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$$   
Copy after login

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 ;
Copy after login

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 ;
Copy after login

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$$   
  
  
Copy after login

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 ; 
  
Copy after login

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$$   
Copy after login

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$$   
Copy after login

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)
Copy after login

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> 
Copy after login

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> 
Copy after login

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> 
Copy after login

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> 
Copy after login

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>
Copy after login

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> 
Copy after login

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)
Copy after login

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>
Copy after login

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>
Copy after login

 


Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
2 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Windows 11: The easy way to import and export start layouts Windows 11: The easy way to import and export start layouts Aug 22, 2023 am 10:13 AM

In Windows 11, the Start menu has been redesigned and features a simplified set of apps arranged in a grid of pages, unlike its predecessor, which had folders, apps, and apps on the Start menu. Group. You can customize the Start menu layout and import and export it to other Windows devices to personalize it to your liking. In this guide, we’ll discuss step-by-step instructions for importing Start Layout to customize the default layout on Windows 11. What is Import-StartLayout in Windows 11? Import Start Layout is a cmdlet used in Windows 10 and earlier versions to import customizations for the Start menu into

How to Default 'Show More Options' in Windows 11's Right-Click Menu How to Default 'Show More Options' in Windows 11's Right-Click Menu Jul 10, 2023 pm 12:33 PM

One of the most annoying changes that we users never want is the inclusion of "Show more options" in the right-click context menu. However, you can remove it and get back the classic context menu in Windows 11. No more multiple clicks and looking for these ZIP shortcuts in context menus. Follow this guide to return to a full-blown right-click context menu on Windows 11. Fix 1 – Manually adjust the CLSID This is the only manual method on our list. You will adjust specific keys or values ​​in Registry Editor to resolve this issue. NOTE – Registry edits like this are very safe and will work without any issues. Therefore, you should create a registry backup before trying this on your system. Step 1 – Try it

How to edit messages on iPhone How to edit messages on iPhone Dec 18, 2023 pm 02:13 PM

The native Messages app on iPhone lets you easily edit sent texts. This way, you can correct your mistakes, punctuation, and even autocorrect wrong phrases/words that may have been applied to your text. In this article, we will learn how to edit messages on iPhone. How to Edit Messages on iPhone Required: iPhone running iOS16 or later. You can only edit iMessage text on the Messages app, and then only within 15 minutes of sending the original text. Non-iMessage text is not supported, so they cannot be retrieved or edited. Launch the Messages app on your iPhone. In Messages, select the conversation from which you want to edit the message

Implementation steps of implementing menu navigation bar with shadow effect using pure CSS Implementation steps of implementing menu navigation bar with shadow effect using pure CSS Oct 16, 2023 am 08:27 AM

The steps to implement a menu navigation bar with shadow effect using pure CSS require specific code examples. In web design, the menu navigation bar is a very common element. By adding a shadow effect to the menu navigation bar, you can not only increase its aesthetics, but also improve the user experience. In this article, we will use pure CSS to implement a menu navigation bar with a shadow effect, and provide specific code examples for reference. The implementation steps are as follows: Create HTML structure First, we need to create a basic HTML structure to accommodate the menu navigation bar. by

How to remove the 'Open in Windows Terminal' option from the right-click context menu in Windows 11 How to remove the 'Open in Windows Terminal' option from the right-click context menu in Windows 11 Apr 13, 2023 pm 06:28 PM

By default, the Windows 11 right-click context menu has an option called Open in Windows Terminal. This is a very useful feature that allows users to open Windows Terminal at a specific location. For example, if you right-click on a folder and select the "Open in Windows Terminal" option, Windows Terminal will launch and set that specific location as its current working directory. Although this is an awesome feature, not everyone finds a use for this feature. Some users may simply not want this option in their right-click context menu and want to remove it to tidy up their right-click context menu.

How to disable the Show more options menu in Windows 11 How to disable the Show more options menu in Windows 11 Apr 13, 2023 pm 08:10 PM

More and more people are experiencing the new and improved Microsoft operating system, but it seems that some of them still prefer the old-school design. There's no doubt that the new context menu brings impressive consistency to Windows 11. If we consider Windows 10, the fact that each application has its own context menu element creates serious confusion for some people. From the Windows 11 transparent taskbar to the rounded corners, this operating system is a masterpiece. In this matter, users across the globe are interested to know how to quickly disable Windows 11 Show More Options menu. The process is pretty simple, so if you're in the same boat, make sure you check it out completely

How to reject ads in Windows 11 in 5 easy steps How to reject ads in Windows 11 in 5 easy steps Apr 22, 2023 pm 07:16 PM

We all know ads can be annoying at times. How ads pop up at the least welcome times; how they lead you to unwanted platforms; and worst of all, some ads are known to pose malware threats. So, if you’ve been wondering how to get rid of constant Windows 11 ads but didn’t know how, here’s the help you’ve been waiting for. In this article Why do I get ads in Windows 11? Despite the urgent need to get rid of Windows 11 ads, we think it's worth understanding what triggers these ads and why you're getting them: Features added from recent Windows updates - features like News and Interests can make it difficult to get notifications without them Use your computer. this

How to use JavaScript to achieve the effect of dragging up and down images? How to use JavaScript to achieve the effect of dragging up and down images? Oct 18, 2023 am 09:09 AM

How does JavaScript achieve the effect of dragging up and down images? With the development of the Internet, pictures play an important role in our lives and work. In order to improve the user experience, we often need to add some special effects or interactive effects to pictures. Among them, the effect of dragging up and down pictures to switch is a very common, simple and practical effect. This article will introduce how to use JavaScript to achieve this effect and provide specific code examples. First, we need to create an HTML file to display images and implement dragging

See all articles