MySQL实现递归查询
创建 MySQL function
DELIMITER //
CREATE FUNCTION relationTree (userId INT)
RETURNS VARCHAR(4000)
BEGIN
DECLARE sTemp VARCHAR(4000);
DECLARE sTempChd VARCHAR(4000);
SET sTemp = "$";
SET sTempChd = cast(userId as char);
WHILE sTempChd is not NULL DO
SET sTemp = CONCAT(sTemp,',',sTempChd);
SELECT group_concat(id) INTO sTempChd FROM users where FIND_IN_SET(parent_user_id,sTempChd)>0;
END WHILE;
return sTemp;
END;//
执行查询:
select relationTree(1)
改进:如果记录数量较大,可以先筛选数据创建临时表,然后对临时表进行递归查询