简介: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里面多查几次吧。。。存储结构有很多优点,包括加快查询速度、提高安全性等等,但是会加大数据库负荷,很多文章建议结合使用,个人也觉得少用点会好些。
如对本文有疑问,
点击进行留言回复!!
相关文章:
-
-
-
-
redis数据库1
大纲:理论:数据库分类Redis重要特性redis应用场景实验:安装redisredis基本操作命令redis持...
[阅读全文]
-
第十五周作业作业
1、导入hellodb.sql生成数据库(1)在students表中,查询年龄大于25岁,且为男性的同学的名字和...
[阅读全文]
-
一致性Hash分析
Hash算法应用场景Hash算法在很多分布式集群产品中都有应用,比如分布式集群架构Redis、Hadoop、El...
[阅读全文]
-
-
-
暑期记录
本周学习MySQL安装使用yum安装所需软件包[root@localhost ~]# yum -y instal...
[阅读全文]
-
-
Kafka控制器
1.ZookeeperZookeeper对Kafka集群的管理操作主要是用了它的两个功能节点(临时节点【zook...
[阅读全文]
网友评论