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方面的实现

  <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 ;
© 版权声明
THE END
喜欢就支持一下吧
点赞15 分享
评论 抢沙发

请登录后发表评论