上面列出两个树型查询方法,第3条语句和第5条语句,这两条语句之间的区别在于prior要害字的位置差异,以是抉择了查询的方法差异。 当parent = prior id时,数据库会按照当前的id迭代出parent与该id沟通的记录,以是查询的功效是迭代出了全部的子类记录;而prior parent = id时,数据库会跟据当前的parent来迭代出与当前的parent沟通的id的记录,以是查询出来的功效就是全部的父类功效。
以下是一系列针对树布局的更深条理的查询,这里的查询不必然是最优的查询方法,或者只是个中的一种实现罢了。
6)、查询一个节点的兄弟节点(亲兄弟)。
|
1
2
3
--m.parent=m2.parent-->统一个父亲
select * from tb_menu m
where 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
) a
where b.lev =
1
?
union all
?
select *
from tmp
where 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);
(编辑:湖南网)
【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!