MySQL 递归实现

CREATE DEFINER=`root`@`localhost` FUNCTION `getChildLst`(pId CHAR(32)) RETURNS varchar(1000) CHARSET utf8
BEGIN 
/**
 select * from t_users  where FIND_IN_SET(userId ,getChildLst('admin'))
**/
	DECLARE sTemp VARCHAR(10000);

	DECLARE sTempChd VARCHAR(10000);

	SET sTemp = "-1";

	SET sTempChd =cast(pId as CHAR);

	WHILE sTempChd is not null DO

		SET sTemp = concat(sTemp,',',sTempChd);

		SELECT GROUP_CONCAT(g.userId) INTO sTempChd FROM t_users g where FIND_IN_SET(g.parentId, sTempChd)>0;

	END WHILE;

	RETURN sTemp;

END

你可能感兴趣的:(mysql)