代码之家  ›  专栏  ›  技术社区  ›  js1983

在Oracle中,如何从按子代值过滤的分层查询中选择行?

  •  1
  • js1983  · 技术社区  · 7 年前

    给定表格

    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
    

    我试图做的是查询这个表并从级别1(建筑)获取所有项目,但我需要做的是通过返回包含特定值的子项来过滤这个返回集。下面的查询是到目前为止返回百思买、沃尔玛和亚马逊的查询

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

    子类型 属于 对象 subval公司 属于 ,因此仅返回 百思买 亚马逊 根据我的询问。我真的不确定接下来该怎么办。

    SQLFiddle

    2 回复  |  直到 7 年前
        1
  •  2
  •   Matthew McPeak    7 年前

    尝试反转 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%';
    
        2
  •  1
  •   Jon Ekiz    7 年前

    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