我正在解决一个问题,即从任何“叶子”或孩子开始,我都可以找到孩子的兄弟姐妹和继兄弟姐妹。举一个更好的例子,如果父母A有两个孩子,并且与父母B共享一个孩子,而父母B有两个孩子,一个与父母A共享,一个与父母C共享,而父母c还有两个不与之共享的孩子。父母B,如何报告所有孩子?我尝试过使用递归和分层查询,但似乎无法正确处理。下面是表的结构和值以及到目前为止的尝试。
create table bw_parents(
parent_id char(1) primary key);
create table bw_children(
child_id number(2),
parent_id char(1),
constraint parent_id_fk FOREIGN KEY (parent_id) references bw_parents
);
insert into bw_parents values('A');
insert into bw_parents values('B');
insert into bw_parents values('C');
insert into bw_parents values('D');
insert into bw_parents values('E');
insert into bw_children values(1,'A');
insert into bw_children values(2,'A');
insert into bw_children values(2,'B');
insert into bw_children values(3,'B');
insert into bw_children values(3,'C');
insert into bw_children values(4,'C');
insert into bw_children values(5,'C');
insert into bw_children values(6,'D');
insert into bw_children values(7,'D');
insert into bw_children values(8,'E');
--hierarchical attempt
select A.parent_id, B.child_id, level
from bw_parents A
join bw_children B ON A.parent_id = B.parent_id
start with A.parent_id = 'B'
connect by nocycle prior B.parent_id = B.parent_id
--recursive with
with r as(
select parent_id, null as child_id
from bw_parents
union all
select A.parent_id parent_id, B.child_id child_id
from bw_parents A
join bw_children B ON A.parent_id = B.parent_id)
select *
from r
where parent_id = 'B';
答案 0 :(得分:1)
这是从给定的父级开始的简单(但可能效果不佳)的解决方案:
select distinct child_id
from bw_children
start with parent_id = 'A'
connect by nocycle (mod(level, 2) = 0 and child_id = prior child_id ) or
(mod(level, 2) = 1 and parent_id = prior parent_id)
;
如果必须以child_id
开头,则必须在mod(level, 2)
条件下将0和1切换为connect by
的值;其余的保持不变。