使用 SQL 有没有办法比较一个节点是否在任何一组节点的父层次结构中?

Using SQL is there a way to compare if a node is in the parent hierarchy of any of a set of nodes?

我需要在我的层次结构中搜索 return 高于或等于任何节点 return 在子查询中编辑的所有节点。

给定 table: H

Child | Parent
  A1  | A
  A2  | A
  A1b | A1
  A2a | A2
  A2b | A2
  B1  | B
  B3  | B
  B1c | B1
  B3a | B3

子查询 returns:

A2a
A2b
B3

我需要一个使用子查询结果的查询 return。

A
A2
A2a
A2b
B
B3

我一直在尝试使用 中的查询来解决问题,但到目前为止运气不好。

您可以将现有查询放在 CTE 中,然后像这样设置分层查询:

WITH q(id) AS ( ... )
SELECT id FROM q
UNION ALL
SELECT DISTINCT Parent
FROM mytable
CONNECT BY PRIOR Parent = Child
START WITH Child in (SELECT id FROM q)
ORDER BY id

Demo on DB Fiddle 使用您的示例数据:

WITH q(id) AS (
    SELECT 'A2a' FROM DUAL
    UNION ALL SELECT 'A2b' FROM DUAL
    UNION ALL SELECT 'B3' FROM DUAL
)
SELECT id FROM q
UNION ALL
SELECT DISTINCT Parent
FROM mytable
CONNECT BY PRIOR Parent = Child
START WITH Child in (SELECT id FROM q)
ORDER BY id
| ID  |
| :-- |
| A   |
| A2  |
| A2a |
| A2b |
| B   |
| B3  |