MySQL uses custom functions to recursively query parent ID or child ID

MySQL uses custom functions to recursively query parent ID or child ID

background:

In MySQL, if there is a limited level, for example, if we can determine the maximum depth of the tree in advance, then the depth of all trees with nodes as roots will not exceed the maximum depth of the tree, then we can directly implement it through left join.

But many times we cannot control or know the depth of the tree. At this time, you need to use stored procedures (functions) in MySQL or use recursion in the program to implement it. This article discusses how to use functions in MySQL to achieve:

1. Environmental Preparation

1. Create a table

CREATE TABLE `table_name` (
 `id` int(11) NOT NULL AUTO_INCREMENT,
 `status` int(255) NULL DEFAULT NULL,
 `pid` int(11) NULL DEFAULT NULL,
 PRIMARY KEY (`id`) USING BTREE
) ENGINE = InnoDB AUTO_INCREMENT = 1 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;

2. Insert data

INSERT INTO `table_name` VALUES (1, 12, 0);
INSERT INTO `table_name` VALUES (2, 4, 1);
INSERT INTO `table_name` VALUES (3, 8, 2);
INSERT INTO `table_name` VALUES (4, 16, 3);
INSERT INTO `table_name` VALUES (5, 32, 3);
INSERT INTO `table_name` VALUES (6, 64, 3);
INSERT INTO `table_name` VALUES (7, 128, 6);
INSERT INTO `table_name` VALUES (8, 256, 7);
INSERT INTO `table_name` VALUES (9, 512, 8);
INSERT INTO `table_name` VALUES (10, 1024, 9);
INSERT INTO `table_name` VALUES (11, 2048, 10);

2. Writing MySQL functions

1. Query all parent nodes of the current node

delimiter // 
CREATE FUNCTION `getParentList`(root_id BIGINT) 
   RETURNS VARCHAR(1000) 
   BEGIN 
     DECLARE k INT DEFAULT 0;
     DECLARE fid INT DEFAULT 1;
     DECLARE str VARCHAR(1000) DEFAULT '$';
     WHILE rootId > 0 DO
       SET fid=(SELECT pid FROM table_name WHERE root_id=id); 
       IF fid > 0 THEN
         SET str = concat(str,',',fid);  
         SET root_id = fid; 
       ELSE 
         SET root_id=fid; 
       END IF; 
   END WHILE;
   RETURN str;
 END //
 delimiter ;

2. Query all child nodes of the current node

delimiter //
CREATE FUNCTION `getChildList`(root_id BIGINT) 
  RETURNS VARCHAR(1000) 
  BEGIN 
   DECLARE str VARCHAR(1000); 
   DECLARE cid VARCHAR(1000); 
   DECLARE k INT DEFAULT 0;
   SET str = '$'; 
   SET cid = CAST(root_id AS CHAR);12 WHILE cid IS NOT NULL DO 
        IF k > 0 THEN
         SET str = CONCAT(str,',',cid);
        END IF;
        SELECT GROUP_CONCAT(id) INTO cid FROM table_name WHERE FIND_IN_SET(pid,cid)>0;
        SET k = k + 1;
   END WHILE; 
   RETURN str; 
END // 
delimiter ;

3. Testing

1. Get all parents of the current node

SELECT getParentList(10);

2. Get all bytes of the current node

SELECT getChildList(3);

Summarize

The above is what I introduced to you about how to use custom functions in MySQL to recursively query the parent ID or child ID. I hope it will be helpful to you. If you have any questions, please leave me a message and I will reply to you in time. I would also like to thank everyone for their support of the 123WORDPRESS.COM website!
If you find this article helpful, please feel free to reprint it and please indicate the source. Thank you!

You may also be interested in:
  • MySQL recursive query tree table child nodes, parent nodes specific implementation
  • Implementation method of Mysql tree recursive query
  • How to implement recursive query in MYSQL
  • MySql8 WITH RECURSIVE recursive query parent-child collection method
  • Simple usage example of MySQL 8.0 recursive query

<<:  Solution to the error when calling yum in docker container

>>:  jQuery implements dynamic tag event

Recommend

Detailed explanation of the use of MySQL select cache mechanism

MySQL Query Cache is on by default. To some exten...

Summary of commonly used CSS encapsulation methods

1. pc-reset PC style initialization /* normalize....

HTML table markup tutorial (6): dark border color attribute BORDERCOLORDARK

In a table, you can define the color of the lower...

Application of HTML and CSS in Flash

Application of HTML and CSS in Flash: I accidental...

Vue monitoring properties and calculated properties

Table of contents 1. watch monitoring properties ...

docker logs - view the implementation of docker container logs

You can view the container logs through the docke...

How to install mysql5.7.24 binary version on Centos 7 and how to solve it

MySQL binary installation method Download mysql h...

Some methods to optimize query speed when MySQL processes massive data

In the actual projects I participated in, I found...

Vue echarts realizes dynamic display of bar chart

This article shares the specific code of vue echa...

A brief discussion on Linux virtual memory

Table of contents origin Virtual Memory Paging an...

An article explains Tomcat's class loading mechanism

Table of contents - Preface - - JVM Class Loader ...

The use of v-model in vue3 components and in-depth explanation

Table of contents Use two-way binding data in v-m...