Mysql 樹形結構表遞歸父級節點函數方法

地區表

經過當前節點編號查詢父級全部編號集合,經過逗號進行分隔(倒序,包含自身編號)node

-- 經過當前節點編號查詢父級全部編號集合,經過逗號進行分隔(倒序,包含自身編號)
-- DROP FUNCTION `getDistrictParentIds`;
CREATE FUNCTION `getDistrictParentIds`(nodeId varchar(100)) 
RETURNS varchar(1000) 
BEGIN 
DECLARE pid varchar(100) default ''; 
DECLARE ids varchar(1000) default nodeId; 
 
WHILE nodeId is not null  do 
	SET pid =(SELECT district_pid FROM district WHERE district_id = nodeId); 
	IF pid is not null THEN 
		SET ids = concat(ids, ',', pid); 
		SET nodeId = pid; 
	ELSE 
		SET nodeId = pid; 
	END IF; 
END WHILE; 
return ids;
END

經過當前節點編號查詢父級全部名稱集合,經過逗號進行分隔(正序,包含自身名稱)code

-- 經過當前節點編號查詢父級全部名稱集合,經過逗號進行分隔(正序,包含自身名稱)
-- DROP FUNCTION `getDistrictParentNames`;
CREATE FUNCTION `getDistrictParentNames`(nodeId varchar(100)) 
RETURNS varchar(1000) 
BEGIN 
DECLARE pid varchar(100) default ''; 
DECLARE ids varchar(1000) default nodeId; 
 
WHILE nodeId is not null  do 
	SET pid =(SELECT district_pid FROM district WHERE district_id = nodeId); 
	IF pid is not null THEN 
		SET ids = concat(ids, ',', pid); 
		SET nodeId = pid; 
	ELSE 
		SET nodeId = pid; 
	END IF; 
END WHILE; 
return (select group_concat(district_name order by district_id) from district where FIND_IN_SET(district_id,ids) );
END

行業表

經過當前節點編號查詢父級全部編號集合,經過逗號進行分隔(倒序,包含自身編號)get

-- 經過當前節點編號查詢父級全部編號集合,經過逗號進行分隔(倒序,包含自身編號)
-- DROP FUNCTION `getIndustryParentIds`;
CREATE FUNCTION `getIndustryParentIds`(nodeId varchar(100)) 
RETURNS varchar(1000) 
BEGIN 
DECLARE pid varchar(100) default ''; 
DECLARE ids varchar(1000) default nodeId; 
 
WHILE nodeId is not null  do 
	SET pid =(SELECT industry_pid FROM industry WHERE industry_id = nodeId); 
	IF pid is not null THEN 
		SET ids = concat(ids, ',', pid); 
		SET nodeId = pid; 
	ELSE 
		SET nodeId = pid; 
	END IF; 
END WHILE; 
return ids;
END

經過當前節點編號查詢父級全部名稱集合,經過逗號進行分隔(正序,包含自身名稱)select

-- 經過當前節點編號查詢父級全部名稱集合,經過逗號進行分隔(正序,包含自身名稱)
DROP FUNCTION `getIndustryParentNames`;
CREATE FUNCTION `getIndustryParentNames`(nodeId varchar(100)) 
RETURNS varchar(1000) 
BEGIN 
DECLARE pid varchar(100) default ''; 
DECLARE ids varchar(1000) default nodeId; 
 
WHILE nodeId is not null  do 
	SET pid =(SELECT industry_pid FROM industry WHERE industry_id = nodeId); 
	IF pid is not null THEN 
		SET ids = concat(ids, ',', pid); 
		SET nodeId = pid; 
	ELSE 
		SET nodeId = pid; 
	END IF; 
END WHILE; 
return (select group_concat(industry_name order by industry_level) from industry where FIND_IN_SET(industry_id,ids));
END
相關文章
相關標籤/搜索