Fork me on GitHub

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方面的博客:https://blog.csdn.net/u014427391/article/details/84996259

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 &lt;>u.para_unit_code
	</select>

Mysql递归查询
下面主要介绍Mysql方面的实现,Mysql并没有提供类似函数,所以只能通过自定义函数实现,网上很多这种资料,不过已经不知道那篇是原创了,这篇博客写的不错,https://www.2cto.com/database/201209/152513.html, 下面我也是用作者提供的方法实现自己的,先感谢作者的分享

这里借用作者提供的自定义函数,再加上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 ;
posted @ 2019-02-14 23:02  smileNicky  阅读(9211)  评论(1编辑  收藏  举报