CREATE FUNCTION fn_get_child(rootId INT,deep INT) RETURNS varchar(4000) CHARSET utf8 #rootId is the node you want to query #deep is the level you want to query BEGIN #declare two temporary variables DECLARE temp VARCHAR(4000); DECLARE temp_child VARCHAR(4000); DECLARE n INT DEFAULT 2; SET temp = '$'; SET temp_child = CAST(rootId AS CHAR);#Force rootId to character SET n = deep; WHILE temp_child is not null DO SET temp = CONCAT(temp,',',temp_child);#The loop connects all nodes into a string. SELECT GROUP_CONCAT(id) INTO temp_child FROM address where FIND_IN_SET(parent_id,temp_child)>0; set n = n-1; END WHILE; RETURN temp; END