当前位置: 移动技术网 > IT编程>数据库>Mysql > Mysql树形递归查询的实现方法

Mysql树形递归查询的实现方法

2019年03月18日  | 移动技术网IT编程  | 我要评论

前言

对于数据库中的树形结构数据,如部门表,有时候,我们需要知道某部门的所有下属部分或者某部分的所有上级部门,这时候就需要用到mysql的递归查询

最近在做项目迁移,oracle版本的迁到mysql版本,遇到有些oracle的函数,mysql并没有,所以就只好想自定义函数或者找到替换函数的方法进行改造。

oracle递归查询

oracle实现递归查询的话,就可以使用start with ... connect by

connect by递归查询基本语法是:

select 1 from 表格 start with ... connect by prior id = pid

start with:表示以什么为根节点,不加限制可以写1=1,要以id为123的节点为根节点,就写为start with id =123

connect by:connect by是必须的,start with有些情况是可以省略的,或者直接start with 1=1不加限制

prior:prior关键字可以放在等号的前面,也可以放在等号的后面,表示的意义是不一样的,比如 prior id = pid,就表示pid就是这条记录的根节点了

具体可以参考我以前写的一篇oracle方面的博客:

oracle方面的实现

<select id="listunitinfo" resulttype="com.admin.system.unit.model.unitmodel" databaseid="oracle">
 select distinct u.unit_code,
 u.unit_name,
 u.unit_tel,
 u.para_unit_code
 from lzcity_approve_unit_info u
 start with 1 = 1
 <if test="unitcode != null and unitcode !=''">
 and u.unit_code = #{unitcode}
 </if>
 <if test="unitname!=null and unitname!=''">
 and u.unit_name like '%'|| #{unitname} ||'%'
 </if>
 connect by prior u.unit_code = u.para_unit_code
 and u.unit_code <>u.para_unit_code
 </select>

mysql递归查询

下面主要介绍mysql方面的实现,mysql并没有提供类似函数,所以只能通过自定义函数实现,网上很多这种资料,不过已经不知道那篇是原创了,这篇博客写的不错,, 下面我也是用作者提供的方法实现自己的,先感谢作者的分享

这里借用作者提供的自定义函数,再加上find_in_set函数 find_in_set(u.unit_code,getunitchildlist(#{unitcode})) ,getunitchildlist是自定义函数

<select id="listunitinfo" resulttype="com.admin.system.unit.model.unitmodel" databaseid="mysql">
 select distinct u.unit_code,
  u.unit_name,
  u.unit_tel,
  u.para_unit_code
  from t_unit_info u
  <where>
  <if test="unitcode != null and unitcode !=''">
  and find_in_set(u.unit_code,getunitchildlist(#{unitcode}))
  </if>
  <if test="unitname!=null and unitname!=''">
  and u.unit_name like concat('%', #{unitname} ,'%')
  </if>
  </where>
 </select>

getunitchildlist自定义函数

delimiter $$

use `gd_base`$$

drop function if exists `getunitchildlist`$$

create definer=`root`@`%` function `getunitchildlist`(rootid int) returns varchar(1000) charset utf8
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(unit_code) into schildtemp from lzcity_approve_unit_info where find_in_set(para_unit_code,schildtemp)>0;
 end while;
 return schildlist;
end$$

delimiter ;

总结

以上就是这篇文章的全部内容了,希望本文的内容对大家的学习或者工作具有一定的参考学习价值,如果有疑问大家可以留言交流,谢谢大家对移动技术网的支持。

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

相关文章:

验证码:
移动技术网