`
一帆过海
  • 浏览: 15569 次
  • 性别: Icon_minigender_1
  • 来自: 济南
最近访客 更多访客>>
社区版块
存档分类
最新评论

递归 查询父节点

阅读更多

 

基本语法: 

select ... from tablename start with 条件1 

connect by 条件2 

where 条件3;

 

例:

 

-- 查询出节点 'si' 的父节点,以及父节点的父节点,直到根。
select * from tableName
start with child = 'si'
connect by prior father = child;
 

解释:

将一个树状结构存储在一张表里,表中存在两个字段: child,parent

按字面意思来,每条记录中的parent为child的父节点,这样就可以形成一个树状结构。 

用上述语法的查询可以取得这棵树的所有记录。 

 

条件1 是结点的限定语句,上例子中是叶子节点限定语句。

条件2 是连接条件,上例子中意思是:(prior)前一条记录中的father节点作为下一条记录的child节点

条件3 不解释

 

猜想执行过程:

 

-- 初始化

declare nodeId ...

set nodeId = 'si'

 

-- 查询

select * from tableName

where child = nodeId

 

-- 赋值

 

set nodeId = (select father from tableName where child = nodeId)

 

-- Jump to 查询

 

中间结果:

child father

 si     si0

 

child father

 si     si0

 si0    si1

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics