Home Database Mysql Tutorial MySQL implements tree traversal (questions about multi-level menu bars and multi-level upper and lower departments)

MySQL implements tree traversal (questions about multi-level menu bars and multi-level upper and lower departments)

Feb 16, 2017 pm 01:14 PM

Foreword:
About tree traversal of upper and lower levels of departments in multi-level menu bars or permission systems, oracle There is connect by in MySQL to achieve this. MySQL does not have such a convenient way, so MySQL traversing the data table is a headache we often encounter. The following is implemented through stored procedures.



1, create test table and data:

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

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, using temporary tables and recursion The process implements tree traversal (mysql's UDF cannot be called recursively):

2.1, traverse from a certain node downwards to the child Node, recursively generate temporary table data
##

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

-- 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, trace upward from a certain node to the root node, and recursively generate temporary table data

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

-- 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, implement a function similar to Oracle SYS_CONNECT_BY_PATH, the recursive process outputs a node id path

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

-- 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, the recursive process outputs a node name path

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

24

25

26

-- 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路径

1

2

3

4

5

6

7

8

9

10

11

12

-- 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路径

1

2

3

4

5

6

7

8

9

10

11

12

-- 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,调用过程输出子节点

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

-- 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,调用过程输出父节点

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

-- 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,从根节点开始显示,显示子节点集合:

1

2

3

4

5

6

7

8

9

10

11

12

13

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,显示首页下面的子节点

1

2

3

4

5

6

7

8

9

10

11

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下面的所有子节点

1

2

3

4

5

6

7

8

9

10

11

12

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,“帮忙”节点有一个子节点,显示出来:

1

2

3

4

5

6

7

8

9

10

11

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,“栏目简介”没有子节点,所以只显示最终节点:

1

2

3

4

5

6

7

8

9

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,显示根节点的父节点

1

2

3

4

5

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,显示“首页”的父节点

1

2

3

4

5

6

7

8

9

10

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

1

2

3

4

5

6

7

8

9

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,显示“帮忙”节点的父节点

1

2

3

4

5

6

7

8

9

10

11

12

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,显示最低层节点“栏目简介”的父节点

1

2

3

4

5

6

7

8

9

10

11

12

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

 以上就是MySQL 实现树形的遍历(关于多级菜单栏以及多级上下部门的查询问题) 的内容,更多相关内容请关注PHP中文网(www.php.cn)!


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)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 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)

The relationship between mysql user and database The relationship between mysql user and database Apr 08, 2025 pm 07:15 PM

In MySQL database, the relationship between the user and the database is defined by permissions and tables. The user has a username and password to access the database. Permissions are granted through the GRANT command, while the table is created by the CREATE TABLE command. To establish a relationship between a user and a database, you need to create a database, create a user, and then grant permissions.

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

RDS MySQL integration with Redshift zero ETL RDS MySQL integration with Redshift zero ETL Apr 08, 2025 pm 07:06 PM

Data Integration Simplification: AmazonRDSMySQL and Redshift's zero ETL integration Efficient data integration is at the heart of a data-driven organization. Traditional ETL (extract, convert, load) processes are complex and time-consuming, especially when integrating databases (such as AmazonRDSMySQL) with data warehouses (such as Redshift). However, AWS provides zero ETL integration solutions that have completely changed this situation, providing a simplified, near-real-time solution for data migration from RDSMySQL to Redshift. This article will dive into RDSMySQL zero ETL integration with Redshift, explaining how it works and the advantages it brings to data engineers and developers.

How to fill in mysql username and password How to fill in mysql username and password Apr 08, 2025 pm 07:09 PM

To fill in the MySQL username and password: 1. Determine the username and password; 2. Connect to the database; 3. Use the username and password to execute queries and commands.

Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Query optimization in MySQL is essential for improving database performance, especially when dealing with large data sets Apr 08, 2025 pm 07:12 PM

1. Use the correct index to speed up data retrieval by reducing the amount of data scanned select*frommployeeswherelast_name='smith'; if you look up a column of a table multiple times, create an index for that column. If you or your app needs data from multiple columns according to the criteria, create a composite index 2. Avoid select * only those required columns, if you select all unwanted columns, this will only consume more server memory and cause the server to slow down at high load or frequency times For example, your table contains columns such as created_at and updated_at and timestamps, and then avoid selecting * because they do not require inefficient query se

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

How to copy and paste mysql How to copy and paste mysql Apr 08, 2025 pm 07:18 PM

Copy and paste in MySQL includes the following steps: select the data, copy with Ctrl C (Windows) or Cmd C (Mac); right-click at the target location, select Paste or use Ctrl V (Windows) or Cmd V (Mac); the copied data is inserted into the target location, or replace existing data (depending on whether the data already exists at the target location).

Understand ACID properties: The pillars of a reliable database Understand ACID properties: The pillars of a reliable database Apr 08, 2025 pm 06:33 PM

Detailed explanation of database ACID attributes ACID attributes are a set of rules to ensure the reliability and consistency of database transactions. They define how database systems handle transactions, and ensure data integrity and accuracy even in case of system crashes, power interruptions, or multiple users concurrent access. ACID Attribute Overview Atomicity: A transaction is regarded as an indivisible unit. Any part fails, the entire transaction is rolled back, and the database does not retain any changes. For example, if a bank transfer is deducted from one account but not increased to another, the entire operation is revoked. begintransaction; updateaccountssetbalance=balance-100wh

See all articles