存储过程的获取所有下级目录

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/supwuq/article/details/79390966

关于获取下级目录的一个存储过程

业务场景:树形结构,根据当前节点获取其所有子集节点。

BEGIN
DECLARE sTemp VARCHAR(1000);
DECLARE sTempChd VARCHAR(1000);

SET sTemp = '0';
SET sTempChd =cast(rootId  as CHAR);

while sTempChd is not NULL  do 
  SET sTemp = concat(sTemp,',',sTempChd);
  select group_concat(t_commcata.CommCataID) into sTempChd  FROM t_commcata WHERE FIND_IN_SET(t_commcata.ParentCommCataID,sTempChd)>0;
end while;

RETURN sTemp;
END

A1

B1             B2

   C1    C2       C3   C4

输入A1  

输出:0,A1,B1,B2,C1,C2,C3,C4

这样的查询是递归查询,每次的插叙结果作为下次的查询条件,这段sql中就是执行一次select 取出一层的节点 上面的结构将会执行三次select  ,而且每次都去遍历所有的数据

第一次A1

第二次B1 ,B2

第三次C1,C2,C3,C4

意味着如果我们有10000条数据。层级目录比较深的时候,7层就要7*1000=70000次 是比较影响效率的。

但是在数据较少,层级不多的情况下很实用,项目用了多次。

后来在项目中用java 写了一点优化,放上来。

private void getDescendantId(List<Commcata> recordList,List<Integer> commcataIds,Integer commcataID){
		List<Integer> ids = getIdByParentId(recordList,commcataID);
		
		if(ids.size()>0){
			commcataIds.addAll(ids);
			for(Integer id:ids)
				getDescendantId(recordList,commcataIds,id);
		}
	}
	
	private List<Integer> getIdByParentId(List<Commcata> recordList,Integer parentId){
		List<Integer> ids = new LinkedList<>();
		for(Commcata record:recordList){
			if(record.getParentCommCataID().equals(parentId))
				ids.add(record.getCommCataID());
		}

参数:recordList 是全部的目录数据,commcatas是查询结果,commcataId是传入的类目ID

其实也没有优化很多,只是把东西放在java 来做。只是一种思路

猜你喜欢

转载自blog.csdn.net/supwuq/article/details/79390966
今日推荐