mysql中实现类似oracle的SYS_CONNECT_BY_PATH功能_MySQL
程序员文章站
2022-04-01 08:47:23
...
oracle中的SYS_CONNECT_BY_PATH函数为开发带来了便利,mysql中如何实现类似的功能呢?
BEGIN
DECLARE sParentList VARCHAR (1000) ;
DECLARE sParentTemp VARCHAR(1000);
SET sParentTemp =CAST(rootId AS CHAR);
WHILE sParentTemp IS NOT NULL DO
IF (sParentList IS NOT NULL) THEN
SET sParentList = CONCAT(sParentTemp,'/',sParentList);
ELSE
SET sParentList = CONCAT(sParentTemp);
END IF;
SELECT GROUP_CONCAT(parent_module_id) INTO sParentTemp FROM TOP_SYS_MODULE WHERE FIND_IN_SET(module_id,sParentTemp)>0;
END WHILE;
RETURN sParentList;
END$$
DELIMITER ;
SELECT module_id,parent_module_id,getParentList(module_id) FROM TOP_SYS_MODULE;
DELIMITER $$
CREATE FUNCTION `getParentList` (rootId VARCHAR (50)) RETURNS VARCHAR (1000)BEGIN
DECLARE sParentList VARCHAR (1000) ;
DECLARE sParentTemp VARCHAR(1000);
SET sParentTemp =CAST(rootId AS CHAR);
WHILE sParentTemp IS NOT NULL DO
IF (sParentList IS NOT NULL) THEN
SET sParentList = CONCAT(sParentTemp,'/',sParentList);
ELSE
SET sParentList = CONCAT(sParentTemp);
END IF;
SELECT GROUP_CONCAT(parent_module_id) INTO sParentTemp FROM TOP_SYS_MODULE WHERE FIND_IN_SET(module_id,sParentTemp)>0;
END WHILE;
RETURN sParentList;
END$$
DELIMITER ;
SELECT module_id,parent_module_id,getParentList(module_id) FROM TOP_SYS_MODULE;