//上查 with tmpTree as ( select * from Tree where Id=2 union all select p.* from tmpTree inner join Tree p on p.Id=tmpTree.ParentId ) select * from tmpTree //下查 with tmpTree as ( select * from Tree where Id=2 union all select s.* from tmpTree inner join Tree s on s.ParentId=tmpTree.Id ) select * from tmpTree
SELECT *,TId.GetLevel() as [level] FROM Tree2 --获取所有层级 DECLARE @ParentTree hierarchyid SELECT @ParentTree=TId FROM Tree2 WHERE Id=2 SELECT *,TId.GetLevel()AS [level] FROM Tree2 WHERE TId.IsDescendantOf(@ParentTree)=1 --获取指定的节点所有下级 DECLARE @ChildTree hierarchyid SELECT @ChildTree=TId FROM Tree2 WHERE Id=3 SELECT *,TId.GetLevel()AS [level] FROM Tree2 WHERE @ChildTree.IsDescendantOf(TId)=1 --获取指定的节点所有上级
SELECT * FROM Tree START WITH Id=2 CONNECT BY PRIOR ID=ParentId --下查 SELECT * FROM Tree START WITH Id=2 CONNECT BY ID= PRIOR ParentId --上查
//定义一个依据ID查询所有父ID为这个指定的ID的字符串列表,以逗号分隔
CREATE DEFINER=`root`@`localhost` FUNCTION `getChildLst`(rootId int,direction int) RETURNS varchar(1000) CHARSET utf8
BEGIN
DECLARE sTemp VARCHAR(5000);
DECLARE sTempChd VARCHAR(1000);
SET sTemp = '$';
IF direction=1 THEN
SET sTempChd =cast(rootId as CHAR);
ELSEIF direction=2 THEN
SELECT cast(ParentId as CHAR) into sTempChd FROM Tree WHERE Id=rootId;
END IF;
WHILE sTempChd is not null DO
SET sTemp = concat(sTemp,',',sTempChd);
SELECT group_concat(id) INTO sTempChd FROM Tree where (direction=1 and FIND_IN_SET(ParentId,sTempChd)>0)
or (direction=2 and FIND_IN_SET(Id,sTempChd)>0);
END WHILE;
RETURN sTemp;
END
//查询方法:
select * from tree where find_in_set(id,getChildLst(1,1));--下查
select * from tree where find_in_set(id,getChildLst(1,2));--上查
CREATE DEFINER=`root`@`localhost` FUNCTION `getChildLst`(rootId int,direction int) RETURNS varchar(1000) CHARSET utf8
BEGIN
DECLARE sTemp VARCHAR(5000);
DECLARE sTempChd VARCHAR(1000);
SET sTemp = '$';
SET sTempChd =cast(rootId as CHAR);
IF direction=1 THEN
WHILE sTempChd is not null DO
SET sTemp = concat(sTemp,',',sTempChd);
SELECT group_concat(id) INTO sTempChd FROM Tree where FIND_IN_SET(ParentId,sTempChd)>0;
END WHILE;
ELSEIF direction=2 THEN
WHILE sTempChd is not null DO
SET sTemp = concat(sTemp,',',sTempChd);
SELECT group_concat(ParentId) INTO sTempChd FROM Tree where FIND_IN_SET(Id,sTempChd)>0;
END WHILE;
END IF;
RETURN sTemp;
END
机械节能产品生产企业官网模板...
大气智能家居家具装修装饰类企业通用网站模板...
礼品公司网站模板
宽屏简约大气婚纱摄影影楼模板...
蓝白WAP手机综合医院类整站源码(独立后台)...苏ICP备2024110244号-2 苏公网安备32050702011978号 增值电信业务经营许可证编号:苏B2-20251499 | Copyright 2018 - 2025 源码网商城 (www.ymwmall.com) 版权所有