让所有父母获得给定元素及其兄弟姐妹

时间:2014-11-05 17:28:13

标签: sql oracle hierarchy

我得到了一些层次结构的表格:

create table t_hier (id number primary key, parent number);
insert into t_hier (id, parent) values(0, null);
insert into t_hier (id, parent) values(1, 0);
insert into t_hier (id, parent) values(2, 0);
insert into t_hier (id, parent) values(3, 1);
insert into t_hier (id, parent) values(4, 1);
insert into t_hier (id, parent) values(5, 2);
insert into t_hier (id, parent) values(6, 2);
insert into t_hier (id, parent) values(7, 5);
insert into t_hier (id, parent) values(8, 5);

select rpad('* ', 2*level, '* ')||id id, parent
from t_hier
connect by prior id = parent
start with parent is null;

ID                   PARENT
____________________ ______
* 0 
* * 1                0
* * * 3              1
* * * 4              1
* * 2                0
* * * 5              2
* * * * 7            5
* * * * 8            5
* * * 6              2

鉴于一些ID我需要得到它的所有父母,祖父母等以及返回元素的每个兄弟(兄弟姐妹,我的意思是只有同一个父母的元素,而不是整个级别),并且还给予元素本身。
所以如果我有id为5的元素,我需要返回0,1,2,5和6 对于id为7的元素,我需要返回0,1,2,5,6,7,8。

我认为只需一个查询就可以完成,如果有人帮我解决这个问题会很棒。

3 个答案:

答案 0 :(得分:1)

with parents as (
  select level lvl, id
  from t_hier
  start with id = 7
  connect by id = prior parent
)
select distinct id from t_hier
where id != 7
start with id in (select id from parents where lvl > 1)
connect by prior id = parent and level <= 2;
  1. 找到所有的前辈
  2. 回去,每个祖父找到他的孩子,但只在第二级
  3. 排除起始ID。

答案 1 :(得分:1)

这可能有所帮助:

with cte_getHierarchy (id,parent)
as 
(
  select t_hier.id,t_hier.parent from t_hier where id = 7
  union all
  select t_hier.id,t_hier.parent from t_hier join cte_getHierarchy on t_hier.id = cte_getHierarchy.parent
),
cte_getsibling (id,parent) 
as 
(
  select cte_getHierarchy.id,cte_getHierarchy.parent from cte_getHierarchy 
  union
  select t_hier.id,t_hier.parent from t_hier join cte_getHierarchy on  t_hier.parent = cte_getHierarchy.parent

)
select id from cte_getsibling where id <> 7;

sql fiddle

答案 2 :(得分:0)

应该是这个:

select rpad('* ', 2*level, '* ')||id id, parent
from t_hier
connect by id = prior parent
start with id = 3
union 
select rpad('* ', 2*level, '* ')||id id, parent
from t_hier
connect by prior id = parent and level = 1
start with parent = (select parent from t_hier where id = 3);

为什么id 7会返回0,1(???),2,5,6,8。 1既不是7的祖先也不是兄弟姐妹。