MYSQL树结构,查询所有子元素ID,函数
-- ppid参数(因为和下边pid重复),查询sql自行替换,数据库名自行替换 CREATE DEFINER=`by`@`%` FUNCTION `getUserChilds`(`ppid` INT) RETURNS varchar(4000) CHARSET utf8 NO SQL BEGIN DECLARE sTemp VARCHAR(4000); DECLARE sTempChd VARCHAR(4000); SET sTemp=''; SET sTempChd = CAST(ppid AS CHAR); WHILE sTempChd IS NOT NULL DO SET sTemp= CONCAT(sTemp,',',sTempChd); SELECT GROUP_CONCAT(id) INTO sTempChd FROM by_user WHERE FIND_IN_SET(pid,sTempChd)>0; END WHILE; RETURN sTemp ; END -- 返回的是 '1,2,3,4,5' 的字符串 -- pid参数, 查询sql如下: select * from user bul where FIND_IN_SET(id, getUserChilds(pid))