MySQL recursive query tree data

Source: Internet
Author: User

Create a new table:

CREATE TABLE ' tree ' (  ' id ' int (one) not NULL auto_increment COMMENT ' primary key ',  ' parent_id ' int (one) ' NOT null,  ' name ' varchar (ten) not NULL,  PRIMARY KEY (' id ')) engine=innodb  DEFAULT Charset=utf8;

  

Create a new function (refer to https://jingyan.baidu.com/article/647f01158ee0da7f2148a80b.html):

Drop FUNCTION if EXISTS getchildlst; CREATE FUNCTION ' Getchildlst ' (Rootid INT)  RETURNS varchar (+)  BEGIN  DECLARE stemp varchar (+);  DECLARE stempchd VARCHAR (+);  SET stemp = ' ^ ';  SET stempchd =cast (Rootid as CHAR);  While Stempchd was not a null do  SET stemp = concat (stemp, ', ', stempchd);  SELECT Group_concat (ID) into stempchd from tree where Find_in_set (parent_id,stempchd) >0;  END while;  RETURN stemp;  END  ;

Fill in the data:

ID parent_id Name

1 0 Root nodes
2 level 11 nodes
3 level 11 nodes
4 level 11 nodes
5 Level 32 Nodes
6 Level 42 Nodes
7 Level 22 Nodes
8 Level 53 Nodes
9 Level 53 Nodes
10 Level 53 Nodes
11 Level 63 Nodes
12 Level 114 Nodes
13 Level 104 Nodes

Query ID 1 node's child node ID splicing string:select Getchildlst (1));

Results: ^,1,2,3,4,5,6,7,8,9,10,11,12,13

Query tree Data results:SELECT * from tree where Find_in_set (ID, Getchildlst (5));

Results:

ID parent_id Name

5 Level 32 Nodes

8 Level 53 Nodes
9 Level 53 Nodes
10 Level 53 Nodes
13 Level 104 Nodes

MySQL recursive query tree data

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.