SQL Oracle层次结构查询获取所有父项和子项

时间:2017-03-30 03:16:11

标签: oracle parent-child hierarchical-data connect-by

我正在尝试构建一个返回所有父项和所有子项的SQL查询。

第一个SQL返回给定基础的所有父级

    SELECT BASE,
         LISTAGG (PARENT_ENTITY_ID, ';') WITHIN GROUP (ORDER BY BASE)
            AS PARENTS
    FROM (    SELECT CONNECT_BY_ROOT CHILD_ENTITY_ID BASE,
                     CHILD_ENTITY_ID,
                     PARENT_ENTITY_ID
                FROM P360_RCT_ENTTY_RLTNSHP
          CONNECT BY PRIOR PARENT_ENTITY_ID = CHILD_ENTITY_ID)
GROUP BY BASE

第二个SQL返回给定基础的所有子项

SELECT BASE,
         LISTAGG (CHILD_ENTITY_ID, ';') WITHIN GROUP (ORDER BY BASE)
            AS CHILDREN
    FROM (    SELECT CONNECT_BY_ROOT PARENT_ENTITY_ID BASE,
                     CHILD_ENTITY_ID,
                     PARENT_ENTITY_ID
                FROM P360_RCT_ENTTY_RLTNSHP
          CONNECT BY PRIOR CHILD_ENTITY_ID=PARENT_ENTITY_ID)
GROUP BY BASE

有没有办法在我传递基础的单个SQL查询中返回它们,我得到一个子列表和父项?我在SO上搜索并发现了几个与该主题相关的问题,但没有具体说明在一个查询中同时获得父母和孩子。

0 个答案:

没有答案