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

Share the pitfalls of MySQL's current_timestamp and their solutions

Table of contents MySQL's current_timestamp p...

How to quickly build an FTP file service using FileZilla

In order to facilitate the storage and access of ...

JS realizes picture digital clock

This article example shares the specific code of ...

5 issues you should pay attention to when making a web page

1. Color matching problem <br />A web page s...

I have compiled a few cool design sites that I think are good.

You must have inspiration to design a website. Goo...

Solution to nginx not jumping to the upstream address

Preface Today I encountered a very strange proble...

JavaScript to show and hide the drop-down menu

This article shares the specific code for JavaScr...

Samba server configuration under Centos7 (actual combat)

Samba Overview Samba is a free software that impl...

Problems with using wangeditor rich text editing in Vue

wangEditor is a web rich text editor developed ba...

Detailed explanation of the processing of the three Docker Nginx Logs

Because colleagues in the company need Nginx log ...

Typescript+react to achieve simple drag and drop effects on mobile and PC

This article shares the specific code of typescri...

MYSQL's 10 classic optimization cases and scenarios

Table of contents 1. General steps for SQL optimi...

Summary of changes in the use of axios in vue3 study notes

Table of contents 1. Basic use of axio 2. How to ...