I am facing same situation.
I want to fetch all child list of particular parent from same table, where as MySQL is not provided Recursive CTE in below MySQL 8.
I had resolved my issue with recursive store procedure. In that we need to set max_sp_recursion_depth to recursive store procedure call.
My table structure is below

My store procedure(With recursion) is below:
DROP PROCEDURE IF EXISTS getAllChilds;
DELIMITER $$
SET @@SESSION.max_sp_recursion_depth=25; $$
CREATE PROCEDURE getAllChilds (IN inId int(11), INOUT list_obj text, IN end_arr CHAR(1))
BEGIN
DECLARE stop_cur INTEGER DEFAULT 0;
DECLARE _id INTEGER DEFAULT 0;
DECLARE _name VARCHAR(20) DEFAULT 0;
DEClARE curSelfId CURSOR FOR SELECT id, name FROM new_table where parentId = inId;
DECLARE CONTINUE HANDLER FOR NOT FOUND SET stop_cur = 1;
OPEN curSelfId;
getSelfId: LOOP
FETCH curSelfId INTO _id, _name;
IF stop_cur = 1 THEN LEAVE getSelfId; END IF;
IF list_obj is null or list_obj = "" then
SET list_obj = CONCAT("[","{",'"name":"',_name,'","id":"',_id,'"',"}");
else
SET list_obj = CONCAT(list_obj,',', "{",'"name":"',_name,'","id":"',_id,'"',"}");
end if;
CALL getAllChilds(_id,list_obj,"");
END LOOP getSelfId;
CLOSE curSelfId;
IF end_arr is not null and end_arr != "" then
SET list_obj = CONCAT(list_obj,end_arr);
SELECT @ids;
end if;
END$$
DELIMITER ;
To Call this stored procedure we need to pass 3 arguments,
- Parent id
- Empty/null object
End array sign.(for append only last object instead of all objects).
CALL getAllChilds(1,@ids,']');
Using this store procedure you may get all level child in JSON string.
You can parse this json string and convert in any OBJECT using any JSONparser.
Or
we can wrap this answer in store procedure for use it into any programming language like JAVA.
we are wrapping this into store procedure because we can't use := in query.
Here we are using find_in_set function.
My store procedure(Without recursion).
DROP PROCEDURE IF EXISTS getAllChilds;
DELIMITER $$
CREATE PROCEDURE getAllChilds (IN inId int(11))
BEGIN
select id,
name,
parentid
from
(select * from new_table
order by parentid, id) new_table,
(select @pv := inId) initialisation
where
find_in_set(parentid, @pv) > 0
and @pv := concat(@pv, ',', id);
END$$
DELIMITER ;
To call this store procedure we need just parent Id.
CALL getAllChilds(1);