Using MySQL Query to Traverse Rows and Create a Recursive Tree
Problem Statement
In a Bill of Materials (BOM) table with item and parent columns, you need to retrieve a recursive tree structure displaying parent-child relationships. The desired output could involve multiple levels of hierarchy, but currently, you're limited to fetching either a single level or retrieving all records and manually sorting them using a recursive function, which can be inefficient.
Solution
While MySQL itself does not natively support recursive tree traversal, you can utilize stored procedures to achieve the functionality. One approach involves creating three stored procedures:
By calling these stored procedures with the starting item ID, you can recursively traverse the rows in the BOM table and construct the desired tree structure.
Example Stored Procedure:
CREATE PROCEDURE GetFamilyTree(IN start_item_id INT) BEGIN # Declare variables DECLARE parent_id INT; DECLARE ancestry VARCHAR(255); DECLARE done TINYINT DEFAULT 0; # Loop through item IDs until done WHILE NOT done DO # Get parent ID CALL GetParentIDByID(start_item_id, parent_id); # If parent ID is null, we're done IF parent_id IS NULL THEN SET done = 1; LEAVE; END IF; # Append parent ID to ancestry SET ancestry = CONCAT(ancestry, ',', parent_id); # Set current item ID to parent ID SET start_item_id = parent_id; END WHILE; # Return ancestry as result SELECT ancestry; END
Usage:
To retrieve the family tree starting from item ID 1, call the stored procedure:
CALL GetFamilyTree(1);
The result will be a comma-separated string containing the ancestry of item 1.
The above is the detailed content of How Can MySQL Stored Procedures Solve Recursive Tree Traversal in a Bill of Materials Table?. For more information, please follow other related articles on the PHP Chinese website!