5

我在 Oracle 9i 数据库表中有父子关系

像:

parent | child  
1      | 2  
2      | 3
2      | 4
null   | 1
1      | 8

我需要从给定的孩子那里得到绝对的父母。说,我有孩子 4,它必须给我父母:1

我已经查看了 CONNECT BY ,但找不到解决方案。

4

2 回答 2

4

您可以使用 CONNECT BY 查询来构建父母列表,然后过滤:

SQL> WITH tree AS (
  2     SELECT 1 parent_id, 2 child_id FROM DUAL
  3     UNION ALL SELECT 2   , 3  FROM DUAL
  4     UNION ALL SELECT 2   , 4  FROM DUAL
  5     UNION ALL SELECT null, 1  FROM DUAL
  6     UNION ALL SELECT 1   , 8  FROM DUAL
  7  )
  8  SELECT child_id
  9    FROM (SELECT *
 10            FROM tree
 11          CONNECT BY PRIOR parent_id = child_id
 12           START WITH child_id = 4)
 13   WHERE parent_id IS NULL;

  CHILD_ID
----------
         1
于 2009-09-18T14:38:15.223 回答
0
SELECT  parent
FROM    (
        SELECT  parent
        FROM    (
                SELECT  parent, level AS l
                FROM    mytable
                START WITH
                        child = 4
                CONNECT BY
                        child = PRIOR parent
                )
        ORDER BY
                l DESC
        )
WHERE   rownum = 1

这将使您NULL成为绝对的父母。

如果需要1,请替换parentchild

SELECT  child
FROM    (
        SELECT  child
        FROM    (
                SELECT  child, level AS l
                FROM    mytable
                START WITH
                        child = 4
                CONNECT BY
                        child = PRIOR parent
                )
        ORDER BY
                l DESC
        )
WHERE   rownum = 1
于 2009-09-18T14:31:38.073 回答