Example of a MySQL function that recursively acquires the values of the ancestor Element

Source: Internet
Author: User

Test. SQL:

-- Create Test Data
Drop table if exists T1;
Create table T1 (
Id bigint not null auto_increment,
Pid bigint,
Code varchar (255 ),
Primary key (id)
);
Insert into t1 (id, pid, code) values (1, null, '1 ');
Insert into t1 (id, pid, code) values (2, null, '2 ');
Insert into t1 (id, pid, code) values (3, 1, '1. 1 ');
Insert into t1 (id, pid, code) values (4, 1, '1. 2 ');
Insert into t1 (id, pid, code) values (5, 2, '2. 1 ');
Insert into t1 (id, pid, code) values (6, 3, '1. 1.1 ');
Select * from t1 order by code;

-- Define a recursive processing function: Get the id and code of the ancestor and connect them in sequence with the symbol '/'. Connect the id and code ';'.
DELIMITER $
Drop function if exists getAncestors $
Create function getAncestors (id bigint) returns varchar (1000)
BEGIN
DECLARE done int default 0;
DECLARE r VARCHAR (1000 );
DECLARE ri VARCHAR (1000 );
DECLARE rc VARCHAR (1000 );
DECLARE levint;
DECLARE cid bigint;
DECLARE pid bigint;
DECLARE pcode VARCHAR (255 );
Declare continue handler for not found set done = 1;

SET cid = id;
SET lev_= 0;
SET ri = '';
SET rc = '';
REPEAT
SELECT p. id, p. code into pid, pcode FROM T1 c inner join T1 p on p. id = c. pid where c. id = cid;
If not done THEN
SET cid = pid;
If length (ri)> 0 then
SET ri = concat (cast (pid as char), '/', ri );
SET rc = concat (cast (pid as char), '/', rc );
Else
SET ri = cast (pid as char );
SET rc = pcode;
End if;
End if;
UNTIL done end repeat;
If length (ri)> 0 then
SET r = concat (ri, ';', rc );
Else
SET r = null;
End if;
RETURN r;
END $
DELIMITER;
-- Return Value: null;
Select getAncestors (1 );
-- Return Value: '1; 1 ';
Select getAncestors (3 );
-- Return Value: '1970; 1/3. 1 ';
Select getAncestors (6 );

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.