加入收藏 | 设为首页 | 会员中心 | 我要投稿 温州站长网 (https://www.0577zz.com/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

Oracle 树操作、递归查询(select…start with…connect by…prio

发布时间:2021-02-27 04:06:05 所属栏目:百科 来源:网络整理
导读:副标题#e# 一、Oracle中start with…connect by prior子句用法 connect by 是结构化查询中用到的,其基本语法是: select … from tablename start with 条件1 connect by 条件2 where 条件3; 例: select * from table start with org_id = ‘HBHqfWGWPy’
1 2 3 --m.parent=m2.parent-->同一个父亲select * from tb_menu mwhere exists (select * from tb_menu m2 where m.parent=m2.parent and m2.id=6)

7)、查询与一个节点同级的节点(族兄弟)。?如果在表中设置了级别的字段,那么在做这类查询时会很轻松,同一级别的就是与那个节点同级的,在这里列出不使用该字段时的实现!

1 2 3 4 5 6 7 8 with tmp as(??????select a.*,level leaf??????? ??????from tb_menu a??????????????? ??????start with a.parent is null????? ??????connect by a.parent = prior a.id)select *?????????????????????????????? from tmp???????????????????????????? where leaf = (select leaf from tmp where id = 50);

这里使用两个技巧,一个是使用了level来标识每个节点在表中的级别,还有就是使用with语法模拟出了一张带有级别的临时表。

8)、查询一个节点的父节点的的兄弟节点(伯父与叔父)。??????????

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 with tmp as(????select tb_menu.*,level lev????from tb_menu????start with parent is null????connect by parent = prior id)???? select b.*from tmp b,(select *????????????from tmp????????????where id = 21? and lev = 2) awhere b.lev = 1 ? union all ? select *from tmpwhere parent = (select distinct x.id????????????????from tmp x,--祖父?????????????????????tmp y,--父亲?????????????????????(select *??????????????????????from tmp??????????????????????where id = 21? and lev > 2) z --儿子????????????????where y.id = z.parent and x.id = y.parent);

(编辑:温州站长网)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

上面列出两个树型查询方式,第3条语句和第5条语句,这两条语句之间的区别在于prior关键字的位置不同,所以决定了查询的方式不同。 当parent = prior id时,数据库会根据当前的id迭代出parent与该id相同的记录,所以查询的结果是迭代出了所有的子类记录;而prior parent = id时,数据库会跟据当前的parent来迭代出与当前的parent相同的id的记录,所以查询出来的结果就是所有的父类结果。

以下是一系列针对树结构的更深层次的查询,这里的查询不一定是最优的查询方式,或许只是其中的一种实现而已。

6)、查询一个节点的兄弟节点(亲兄弟)。

热点阅读