我在Oracle 9i数据库表中有父子关系
像:
parent | child
1 | 2
2 | 3
2 | 4
null | 1
1 | 8
我需要从给定的孩子那里得到绝对的父母。 说,我有孩子4,它必须给我父母:1
我已经看过CONNECT BY,但我找不到解决方案。
答案 0 :(得分: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
答案 1 :(得分: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
,请将parent
替换为child
:
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