一些简单的查询,应该满足您的要求:
编辑:在查询中添加的评论
EDIT2:最小化了 SYS_CONNECT_BY_PATH 的使用,因此更难达到它的大小限制。
WITH param AS -- this is just our parameter to be used in further subqueries (ID and regex pattern for regexp_like expression)
(
SELECT
57 AS id
,'(\s?)('||57||')(\s|\W)' AS regex
FROM
dual
)
, parent AS -- here we get the inverted hierarchy - searching for the root node of the branch where ID given as parameter exists
(
SELECT
s.*
FROM
company s
,param
CONNECT BY PRIOR s.parent_id = s.id
START WITH s.id = param.id
)
, children AS -- here we get all the children of the root node we found in parent subquery
(
SELECT
s.*
,CASE
WHEN LEVEL >= MAX(CASE WHEN s.id = param.id THEN LEVEL ELSE NULL END) OVER (PARTITION BY NULL) THEN
SYS_CONNECT_BY_PATH(s.id,' ')
ELSE NULL
END AS path -- this gives us the hierarchical path
,LEVEL AS lvl -- this gives us children's levels
,MAX(CASE WHEN s.id = param.id THEN LEVEL ELSE NULL END) OVER (PARTITION BY NULL) AS id_level -- this gives the level of the children given as a parameter
FROM
company s
,param
CONNECT BY PRIOR s.id = s.parent_id
START WITH s.id = (SELECT parent.id FROM parent WHERE parent.parent_id IS NULL)
)
-- now we select from the all children hierarchy our desired branch
SELECT
c.*
FROM
children c
,param
WHERE
1 = CASE WHEN lvl > c.id_level AND REGEXP_LIKE(c.path, param.regex) THEN 1 -- if current id is of higher level (is a child of our paremeter ID), it must have our parameter ID in it's path
WHEN lvl = c.id_level AND c.id = param.id THEN 1 -- if the level is equal to our parameter's ID's leve, it has to be our paremeter
WHEN lvl < c.id_level AND EXISTS(SELECT 1 FROM parent WHERE parent.id = c.id) THEN 1 -- if current level is lower (may be a parent of our parmeter ID) it has to exists in the reverse hierarchy (thus, must be a parent or grandparent etc. of our paremter node)
ELSE 0
END
顺便提一句。在阅读了 Carlo Sirna 的解决方案后,我发现他的解决方案更好:)