DROP TABLE IF EXISTS treenodes;
CREATE TABLE treenodes (
id int(11) NOT NULL,
nodename varchar(20) DEFAULT NULL,
pid int(11) DEFAULT NULL,
PRIMARY KEY (id)
) ENGINE=InnoDB DEFAULT CHARSET=latin1;

INSERT INTO treenodes VALUES ('1', 'A', '0');
INSERT INTO treenodes VALUES ('2', 'B', '1');
INSERT INTO treenodes VALUES ('3', 'C', '1');
INSERT INTO treenodes VALUES ('4', 'D', '2');
INSERT INTO treenodes VALUES ('5', 'E', '2');
INSERT INTO treenodes VALUES ('6', 'F', '3');
INSERT INTO treenodes VALUES ('7', 'G', '6');
INSERT INTO treenodes VALUES ('8', 'H', '0');
INSERT INTO treenodes VALUES ('9', 'I', '8');
INSERT INTO treenodes VALUES ('10', 'J', '8');
INSERT INTO treenodes VALUES ('11', 'K', '8');
INSERT INTO treenodes VALUES ('12', 'L', '9');
INSERT INTO treenodes VALUES ('13', 'M', '9');
INSERT INTO treenodes VALUES ('14', 'N', '12');
INSERT INTO treenodes VALUES ('15', 'O', '12');
INSERT INTO treenodes VALUES ('16', 'P', '15');
INSERT INTO treenodes VALUES ('17', 'Q', '15');

根据传入的ID查询所有的子节点

delimiter // 
CREATE FUNCTION getChildListTreeNodes(rootId INT)
RETURNS varchar(1000)
BEGIN
DECLARE sTemp VARCHAR(1000);
DECLARE sTempChd VARCHAR(1000);
SET sTemp = '$';
SET sTempChd =cast(rootId as CHAR);
WHILE
sTempChd is not null DO
SET sTemp = concat(sTemp,',',sTempChd);
SELECT group_concat(id) INTO sTempChd FROM treenodes where FIND_IN_SET(pid,sTempChd)>0;
END WHILE;
RETURN sTemp;
END
//

常见问题:

Mysql无法创建函数 错误码: 1418 :

show variables like '%func%';

set global log_bin_trust_function_creators =1;

原作者:https://blog.csdn.net/zhangpengself520/article/details/77451805