原文链接:https://www.cnblogs.com/f2flow/p/6001889.html
DROP PROCEDURE IF EXISTS pro_getChildrenList;
CREATE PROCEDURE pro_getChildrenList(IN id VARCHAR(100),IN idFieldName VARCHAR(100),IN parentIdFieldName VARCHAR(100),IN tableName VARCHAR(100),isContainMySelf INT
)BEGINDECLARE lev INT;SET lev=1;DROP TABLE IF EXISTS tmp1;CREATE TABLE tmp1(ID VARCHAR(100),ParentID VARCHAR(100) ,levv INT);SET @strsql = CONCAT('INSERT tmp1' ,' SELECT ', idFieldName ,',' , parentIdFieldName, ',', 1, ' FROM ', tableName, ' WHERE ', parentIdFieldName, '=', '''', id, '''');PREPARE strsql FROM @strsql;EXECUTE strsql;WHILE row_count() > 0DOSET lev=lev+1;SET @strsql = CONCAT('INSERT tmp1', ' SELECT ', 't.', idFieldName, ',' , ' t.',parentIdFieldName, ',' ,lev, ' FROM ', tableName, ' t join tmp1 a on ', 't.', parentIdFieldName, '=a.ID And levv=', lev-1);PREPARE strsql FROM @strsql;EXECUTE strsql;END WHILE;SET @myself='';IF (isContainMySelf=1) THENSET @myself = concat(' or ', idFieldName, '=', '''', id, '''');ELSESET @myself = '';END IF;SET @strsql = CONCAT('SELECT * from ', tableName, ' where ', idFieldName, ' in ( SELECT ID from tmp1)', @myself);PREPARE strsql FROM @strsql;EXECUTE strsql;END;