如何在 Oracle 中按后代值筛选分层查询中的 select 行?

How to select rows from a hierarchical query filtering by descendant value in Oracle?

鉴于 table

ID       PARENT_ID      STRVAL      SUBTYPE     SUBVAL
0        null           Chicago     location    city
1        0              Best Buy    building    bestbuy
2        0              Walmart     building    walmart
3        0              Amazon      building    amazon
4        1              Macbook     object      macbook
5        2              Sausages    object      sausages
6        3              Macbook     object      macbook
7        3              Tupperware  object      tupperware

我想要做的是查询此 table 并从级别 1(建筑物)获取所有项目,但我需要做的是过滤此 return 设置的 returning 那些有包含特定值的子项。以下查询是我目前所掌握的 returns Best Buy、Walmart 和 Amazon

SELECT * FROM (
SELECT strval, parent_id, id
FROM stores
where LEVEL = 1
CONNECT BY PRIOR id = parent_id
START WITH parent_id = 0
) 

我想要做的是得到一个 return 其中一个后代具有 objectsubtypemacbooksubval,因此 return 仅 Best BuyAmazon 来自我的查询。我不太确定从这里到哪里去。

SQLFiddle

此连接应为您提供父级为建筑物的 macbook 对象。随意 select 您只需要的栏目:

select *
from
(
select *
from stores
where subtype = 'object' 
and strval = 'Macbook'
) macs
join
(
select *
from stores 
where subtype = 'building'
) bld
on bld.id = macs.parent_id

尝试扭转您的 CONNECT BY 条件并从(即 START WITH)您所知道的开始:

SELECT DISTINCT strval, parent_id, id
FROM stores
where subtype = 'building'
CONNECT BY id = prior parent_id
START WITH subtype = 'object' and subval = 'macbook';

更一般问题的更新

在评论中,您问如果起始值不在同一水平怎么办?

在那种情况下,恐怕您必须查看每个建筑物的整棵树,然后进行过滤。

我将这一行添加到您的测试数据中:

insert into stores values (8, 4, 'Year','edition','2015');

那么,这个查询给出了答案:

WITH whole_tree AS
       (SELECT strval,
               parent_id,
               id,
               CONNECT_BY_ROOT(strval) building,
               SYS_CONNECT_BY_PATH (subtype || ':' || subval, ',') PATH
        FROM   stores
        CONNECT BY PRIOR id = parent_id
        START WITH subtype = 'building')
SELECT distinct building
FROM   whole_tree
WHERE  PATH LIKE '%object:macbook%edition:2015%';