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 ;


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM