mysql 递归查询父节点 和子节点
Posted 卓扬
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了mysql 递归查询父节点 和子节点相关的知识,希望对你有一定的参考价值。
查父集合
--drop FUNCTION `getParentList` CREATE FUNCTION `getParentList`(rootId varchar(100)) RETURNS varchar(1000) BEGIN DECLARE fid varchar(100) default ‘‘; DECLARE str varchar(1000) default rootId; WHILE rootId is not null do SET fid =(SELECT parentid FROM treeNodes WHERE id = rootId); IF fid is not null THEN SET str = concat(str, ‘,‘, fid); SET rootId = fid; ELSE SET rootId = fid; END IF; END WHILE; return str; END
查询语句
select getParentList(‘001001001001001‘); select * from sbkfwh where FIND_IN_SET(id,getParentList(‘001001001001002‘))
查子集合
--drop FUNCTION `getChildList` CREATE FUNCTION `getChildList`(rootId varchar(100)) RETURNS varchar(2000) BEGIN DECLARE str varchar(2000); DECLARE cid varchar(100); SET str = ‘$‘; SET cid = rootId; WHILE cid is not null DO SET str = concat(str, ‘,‘, cid); SELECT group_concat(id) INTO cid FROM treeNodes where FIND_IN_SET(parentid, cid) > 0; END WHILE; RETURN str; END
查询语句
select getParentList(‘001001001‘); select * from sbkfwh where FIND_IN_SET(id,getChildList(‘001001001‘))
以上是关于mysql 递归查询父节点 和子节点的主要内容,如果未能解决你的问题,请参考以下文章