我希望我能够解释困扰我的问题。 我有以下分层数据集(这只是34K记录的子集)
PARENT_ID CHILD_ID EXAM
TUDA12802 TUDA12982 N
TUDA12982 TUDA12984 J
TUDA12984 TUDA999 J
TUDA12982 TUDA12983 N
TUDA12983 TUDA15322 J
TUDA12983 TUDA15323 J
这是树的表示
TUDA12982 N
- TUDA12984 J
-- TUDA999 J
- TUDA12983 N
-- TUDA15322 J
-- TUDA15323 J
我需要的是所有记录的列表,其中包含考试= N和基础考试='J'记录,可以嵌套。
select *
from test1
connect by prior child_id = parent_id
start with child_id = 'TUDA12982'
order siblings by child_id;
给我
PARENT_ID CHILD_ID EXAM
TUDA12802 TUDA12982 N
TUDA12982 TUDA12984 J
TUDA12984 TUDA999 J
TUDA12982 TUDA12983 N
TUDA12983 TUDA15323 J
TUDA12983 TUDA15322 J
但我需要的是
TUDA12802 TUDA12982 N
TUDA12982 TUDA12984 J
TUDA12984 TUDA999 J
当遇到EXAM ='N'记录时,遍历需要停止。
我需要像'停止'一样的条款。
select *
from test1
connect by prior child_id = parent_id
start with child_id = 'TUDA12982'
stop with exam = 'N'
order siblings by child_id;
如何做到这一点?
答案 0 :(得分:4)
罗伯特,
您可以通过在connect by子句中添加“exam ='J'”来完成此操作:
SQL> create table test1(parent_id,child_id,exam)
2 as
3 select 'TUDA12802', 'TUDA12982', 'N' from dual union all
4 select 'TUDA12982', 'TUDA12984', 'J' from dual union all
5 select 'TUDA12984', 'TUDA999', 'J' from dual union all
6 select 'TUDA12982', 'TUDA12983', 'N' from dual union all
7 select 'TUDA12983', 'TUDA15322', 'J' from dual union all
8 select 'TUDA12983', 'TUDA15323', 'J' from dual
9 /
Tabel is aangemaakt.
SQL> select parent_id
2 , child_id
3 , exam
4 , level
5 , lpad(' ',2*level) || sys_connect_by_path(parent_id||'-'||child_id,'/') scbp
6 from test1
7 start with exam = 'N'
8 connect by prior child_id = parent_id
9 and exam = 'J'
10 /
PARENT_ID CHILD_ID E LEVEL SCBP
--------- --------- - ------ ----------------------------------------------------------------------
TUDA12802 TUDA12982 N 1 /TUDA12802-TUDA12982
TUDA12982 TUDA12984 J 2 /TUDA12802-TUDA12982/TUDA12982-TUDA12984
TUDA12984 TUDA999 J 3 /TUDA12802-TUDA12982/TUDA12982-TUDA12984/TUDA12984-TUDA999
TUDA12982 TUDA12983 N 1 /TUDA12982-TUDA12983
TUDA12983 TUDA15322 J 2 /TUDA12982-TUDA12983/TUDA12983-TUDA15322
TUDA12983 TUDA15323 J 2 /TUDA12982-TUDA12983/TUDA12983-TUDA15323
6 rijen zijn geselecteerd.
此致 罗布。
答案 1 :(得分:0)
听起来像是一个获取所请求项目的简单查询,而'J'孩子就是你想要的,所以这不会起作用:
select *
from test1
where child_id = 'TUDA12982'
or exam = 'J'
connect by prior child_id = parent_id
start with child_id = 'TUDA12982'
order siblings by child_id;
我没有Oracle所以我无法测试它是否有效,但是根据我对语法的理解以及我刚刚用Google搜索它看起来它会起作用。