MySQL recursive sorting query + Tree node generation

Source: Internet
Author: User

Mysql recursive sorting Query

Note: producttype sorting table, producttype. Ptype parent node, producttype. Id Primary Key, showTreeNodes (IN rootid INT) function. The parameter is of the starting type.

Drop procedure if exists showTreeNodes;

Create procedure showTreeNodes (IN rootid INT)
BEGIN
DECLARE Level int;
Drop table if exists tmpLst;
Create table tmpLst (
Id int,
NLevel int,
SCort varchar (8000)
);
Set Level = 0;
INSERT into tmpLst SELECT id, Level, id from producttype WHERE ptype = rootid;
WHILE ROW_COUNT ()> 0 DO
SET Level = Level + 1;
INSERT into tmpLst
Select a. ID, Level, concat (B. sCort, A. ID) FROM producttype A, tmpLst B
Where a. ptype = B. id and B. nLevel = Level-1;
End while;
END;
CALL showTreeNodes (-1 );

SELECT concat (SPACE (B. nLevel * 2), 'signature', A. name)
FROM producttype A, tmpLst B
Where a. ID = B. ID
Order by B. sCort;

Related Article

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.