表结构
节点编号 | 上级节点 | 节点名称 |
---|
id | parend_id | name |
最终需要查询的效果
先定义 一个 递归查询上级 的 函数
DELIMITER $$
USE `1609a`$$
DROP FUNCTION IF EXISTS `getParents`$$
CREATE DEFINER=`root`@`%` FUNCTION `getParents`(self_Id VARCHAR(40))
RETURNS VARCHAR(1000) CHARSET utf8
BEGIN
DECLARE sTemp text(40000);
DECLARE sTempChd text(40000);
DECLARE counts int;
SET sTemp = "";
SET sTempChd =self_Id;
set counts = 0;
WHILE sTempChd IS NOT NULL DO
SET sTemp = CONCAT(sTempChd,"/",sTemp);
select count(*) INTO counts FROM tb_item_cat WHERE id = sTempChd;
IF (counts=0)THEN
set sTempChd = NULL ;
else
SELECT parent_Id INTO sTempChd FROM tb_item_cat WHERE id = sTempChd;
END IF;
END WHILE;
RETURN left(sTemp,length(sTemp)-1);
END$$
DELIMITER
查询sql
select t1.id,t1.name,t2.name ,getParents(t1.id) as path from tb_item_cat t1 left join tb_item_cat t2 on t1.parent_id = t2.id
sql 查询 的结果