当前位置: 移动技术网 > IT编程>数据库>Mysql > MySQL递归查询树状表的子节点、父节点具体实现

MySQL递归查询树状表的子节点、父节点具体实现

2017年12月12日  | 移动技术网IT编程  | 我要评论
简介:mysql5.0.94版本,该版本以及较高级的版本(5.5、6等等)尚未支持循环递归查询,和sqlserver、oracle相比,mysql难于在树状表中层层遍历的子节点。本程序重点参考了下面的资料,写了两个sql存储过程,子节点查询算是照搬了,父节点查询是逆思维弄的。

表结构和表数据就不公示了,查询的表user_role,主键是id,每条记录有parentid字段(对应该记录的父节点,当然,一个父节点自然会有一个以上的子节点嘛)
复制代码 代码如下:

create function `getchildlist`(rootid int)
returns varchar(1000)
begin
declare schildlist varchar(1000);
declare schildtemp varchar(1000);
set schildtemp =cast(rootid as char);
while schildtemp is not null do
if (schildlist is not null) then
set schildlist = concat(schildlist,',',schildtemp);
else
set schildlist = concat(schildtemp);
end if;
select group_concat(id) into schildtemp from user_role where find_in_set(parentid,schildtemp)>0;
end while;
return schildlist;
end;
/*获取子节点*/
/*调用: 1、select getchildlist(0) id; 2、select * 5from user_role where find_in_set(id, getchildlist(2));*/


create function `getparentlist`(rootid int)
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(parentid) into sparenttemp from user_role where find_in_set(id,sparenttemp)>0;
end while;
return sparentlist;
end;
/*获取父节点*/
/*调用: 1、select getparentlist(6) id; 2、select * from user_role where find_in_set(id, getparentlist(2));*/

弄完了,pm说不要弄存储结构,在java里面多查几次吧。。。存储结构有很多优点,包括加快查询速度、提高安全性等等,但是会加大数据库负荷,很多文章建议结合使用,个人也觉得少用点会好些。

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网