【问题标题】:Guidance with SQL SYS_CONNECT_BY_PATHSQL SYS_CONNECT_BY_PATH 指导
【发布时间】:2015-07-25 06:13:29
【问题描述】:

您好,是董事会的新手,一直在浏览类似的主题,但无法找到适合我的用例的查询,如果有人可以帮助我,我将不胜感激!我一直在玩下面的查询,如果我包含一个 CHILD ID,它似乎可以工作,但我想获取 Profile ID = 2 下任何内容的根列表,而不必由每个孩子单独执行。我尝试从 Start With 行中删除 CHILD_ID,但随后我获得了所有配置文件的值。此外,您可以看出每个个人资料都有多个父母

select distinct lpad(' ',2*(level - 1)) || child_id, SYS_CONNECT_BY_PATH(description, '>') ROOT
from mastertable
start with child_id = '1' and profile_id = '2'
connect by nocycle prior child_id = parent_id
PROFILE_ID  CHILD_ID    PARENT_ID   DESCRIPTION
2           2           0           Mailing Address
2           1           0           Legal Address
2           7           1           Address 1
2           8           1           Address 2
2           9           1           Address 3
2           10          1           Address 4
2           11          1           City
2           12          1           State
2           13          1           Country
2           14          1           Zip / Postal Code
2           15          14          Zip / Postal Code
2           16          14          Zip Code
2           17          14          Zip / Postal Code
2           18          1           Special Instructions
3           20          0           Mailing Address
3           21          0           Legal Address
3           22          21          City
3           23          21          State
3           24          21          Country
3           25          21          Zip / Postal Code
3           26          25          Zip / Postal Code
3           27          25          Zip Code
3           28          25          Zip / Postal Code
3           29          21          Special Instructions

【问题讨论】:

  • 我尝试将 child_id 更改为 parent_id=0 但输出似乎不正确,如果我跟踪路径,它肯定不正确。该表有大约 700k 条记录,profile = 2 应该给我大约 2500,但是当我将它更改为 parent_id 时,我得到大约 116k。当我删除 nocycle 我得到一个循环错误
  • 这里是SQL fiddle 与您的数据和查询,它可能对您或回答者有用。我的怀疑是您还应该将and profile id='2' 添加到connect by 条件,但这只是猜测-我无法重现您的示例的差异。

标签: sql oracle recursion hierarchical-data


【解决方案1】:

从那些没有父母的记录开始:

select distinct level, lpad(' ',2*(level - 1)) || child_id, SYS_CONNECT_BY_PATH(description, '>') ROOT
from mastertable m
start with not exists( select null
                       from mastertable
                       where profile_id = m.profile_id
                         and child_id = m.parent_id )
  and profile_id = '2'
connect by nocycle prior child_id = parent_id

@Ponder Stibbons,感谢 SQL 小提琴! Modified query.

【讨论】:

    猜你喜欢
    • 2012-10-09
    • 2021-05-13
    • 2017-10-07
    • 2014-11-24
    • 1970-01-01
    • 2018-06-04
    • 1970-01-01
    • 2012-05-12
    • 2015-09-27
    相关资源
    最近更新 更多