微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

有关数据库SQL递归查询在不同数据库中的实现方法

本文给大家介绍有关数据库sql递归查询在不同数据库中的实现方法,具体内容请看下文。

比如表结构数据如下:

Table:Tree

ID Name ParentId

1 一级 0

2 二级  1

3 三级  2

4 四级  3

sql SERVER 2005查询方法:


rush:sql;"> //上查 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

sql SERVER 2008及以后版本,还可用如下方法

增加一列TID,类型设为:hierarchyid(这个是CLR类型,表示层级),且取消ParentId字段,变成如下:(表名为:Tree2)

TId    Id    Name

0x      1     一级
0x58   2   二级
0x5B40  3  三级
0x5B5E  4  四级

查询方法

rush:sql;"> 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 --获取指定的节点所有上级

ORACLE中的查询方法

rush:sql;"> SELECT * FROM Tree START WITH Id=2 CONNECT BY PRIOR ID=ParentId --下查 SELECT * FROM Tree START WITH Id=2 CONNECT BY ID= PRIOR ParentId --上查

MysqL 中的查询方法

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,2));--上查

补充说明:上面这个方法在下查是没有问题,但在上查时会出现问题,原因在于我的逻辑写错了,存在死循环,现已修正,新的方法如下:

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

这样递归查询就很方便了。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐