mysql get nested records

Solutions on MaxInterview for mysql get nested records by the best coders in the world

showing results for - "mysql get nested records"
Frieda
21 Jan 2018
1DROP PROCEDURE IF EXISTS famsubtree;
2DELIMITER go
3CREATE PROCEDURE famsubtree( root INT )
4BEGIN
5  DROP TABLE IF EXISTS famsubtree;
6  CREATE TABLE famsubtree
7    SELECT childID, parentID, 0 AS level
8    FROM familytree
9    WHERE parentID = root;
10  ALTER TABLE famsubtree ADD PRIMARY KEY(childID,parentID);
11  REPEAT
12    INSERT IGNORE INTO famsubtree
13      SELECT f.childID, f.parentID, s.level+1
14      FROM familytree AS f
15      JOIN famsubtree AS s ON f.parentID = s.childID;
16  UNTIL Row_Count() = 0 END REPEAT;
17END;
18go
19DELIMITER;
20
21And use to query:
22
23call famsubtree(1);       -- from the root you can see forever
24SELECT Concat(Space(level),parentID) AS Parent, Group_Concat(childID ORDER BY childID) AS Child
25FROM famsubtree
26GROUP BY parentID;