Sql 输出与条件匹配的记录,以及它们的父记录到根记录。软件开发工程师
有这样一个Oracle表:Sql 输出与条件匹配的记录,以及它们的父记录到根记录。软件开发工程师,sql,oracle,connect-by,hierarchical-query,Sql,Oracle,Connect By,Hierarchical Query,有这样一个Oracle表: +----+-----+--------+ | ID | PID | NAME | +----+-----+--------+ | 1 | | testX | | 2 | | test2 | | 3 | 2 | test3 | | 4 | 3 | testX | | 5 | 3 | test5 | | 6 | 3 | test6 | | 7 | 4 | test7 | | 8 | 5 | tes
+----+-----+--------+
| ID | PID | NAME |
+----+-----+--------+
| 1 | | testX |
| 2 | | test2 |
| 3 | 2 | test3 |
| 4 | 3 | testX |
| 5 | 3 | test5 |
| 6 | 3 | test6 |
| 7 | 4 | test7 |
| 8 | 5 | test8 |
| 9 | 3 | test9 |
| 10 | 4 | test10 |
| 11 | 5 | testX |
| 12 | 5 | test12 |
+----+-----+--------+
,其中pid是父记录的id
需要输出所有符合条件的记录,以及它们的父记录,直到根记录。
此类父记录不应与在搜索阶段找到的父记录重复
例如,在此条件下,其中name='testX'
,应得到以下结果:
+----+-----+-------+
| ID | PID | NAME |
+----+-----+-------+
| 1 | | testX |
| 2 | | test2 |
| 3 | 2 | test3 |
| 4 | 3 | testX |
| 5 | 3 | test5 |
| 11 | 5 | testX |
+----+-----+-------+
怎么做
p.S.Oracle 11.2.0.4.0。我相信有一种更优雅的方法可以做到这一点,但这就是我想到的 这是生成示例数据的with子句:
with testdata as
(select 1 ID, null PID, 'testX' NAME from dual union all
select 2 , null, 'test2' from dual union all
select 3 , 2, 'test3' from dual union all
select 4 , 3, 'testX' from dual union all
select 5 , 3, 'test5' from dual union all
select 6 , 3, 'test6' from dual union all
select 7 , 4, 'test7' from dual union all
select 8 , 5, 'test8' from dual union all
select 9 , 3, 'test9' from dual union all
select 10, 4, 'test10' from dual union all
select 11, 5, 'testX' from dual union all
select 12, 5, 'test12' from dual)
以下是查询:
select distinct id, pid, name
from(
select sys_connect_by_path(name,'/') path,
id, pid, name
from testdata
connect by prior PID = ID)
where instr(path,'/testX') > 0
order by id
我使用了SYS\u CONNECT\u BY\u PATH
从所有家长那里获取name字段。然后我使用instr
检查testX
是否是字符串中的元素之一
我的结果是:
ID PID NAME
1 testX
2 test2
3 2 test3
4 3 testX
5 3 test5
11 5 testX
这个简单的查询应该有助于-
SELECT distinct id, pid, name FROM tab1
connect by prior pid = id
start with name = 'testX'
order by id
;
输出-
ID PID NAME
1 (null) testX
2 (null) test2
3 2 test3
4 3 testX
5 3 test5
11 5 testX
谢谢你的回答。但是如果有几个条件,并且在树中需要正确的输出顺序,那么该怎么办呢。我下面的回答仅基于您提供的信息。我也不确定您所说的“树中需要正确的输出顺序”是什么意思,例如,如果表中有字段
Code1(varchar2)
和Code2(number)
,则需要按条件进行搜索,其中name='test10'和Code1='test1'和Code2=5
。短语“树中需要正确的输出顺序”,我的意思是我需要对查询应用按
排序兄弟姐妹,例如按名称排序兄弟姐妹,code 2,code 1
。我可以根据史瑞克的回答来做这件事(所需的按
排序兄弟姐妹),但到目前为止,我只使用了对表的两次访问就实现了这一点,因为它看起来像是order-sibbies-by
只在start-with-pid为null的情况下起作用。