我需要SQL查询的帮助。 我有这张桌子:
ITEM PARENT
1 NULL
2 1
3 2
4 2
5 3
6 5
7 5
8 4
9 8
10 1
11 10
12 10
13 8
选择一个项目,我需要以下结果:
选择项目9:家庭清单:8,4,2,1
答案 0 :(得分:1)
您可以使用START WITH
和CONNECT BY
Oracle documentation for Hierarchical Queries
您的案例中的SQL将如下所示
SELECT item
FROM t START WITH item = 9
CONNECT BY PRIOR parent = item
答案 1 :(得分:0)
具体为9
SELECT parent
FROM yourtable
WHERE item = 9
UNION ALL
SELECT parent
FROM yourtable
WHERE item IN (SELECT parent
FROM yourtable y2
WHERE item = 9
AND item = y2.item)
UNION ALL
SELECT parent
FROM yourtable
WHERE item IN (SELECT parent
FROM yourtable
WHERE item IN (SELECT parent
FROM yourtable y2
WHERE item = 9
AND item = y2.item))
UNION ALL
SELECT parent
FROM yourtable
WHERE item IN (SELECT parent
FROM yourtable
WHERE item IN (SELECT parent
FROM yourtable
WHERE item IN (SELECT parent
FROM yourtable y2
WHERE item = 9
AND item = y2.item)))
使用参数@ITEM
SELECT parent
FROM yourtable
WHERE item = @ITEM
UNION ALL
SELECT parent
FROM yourtable
WHERE item IN (SELECT parent
FROM yourtable y2
WHERE item = @ITEM
AND item = y2.item)
UNION ALL
SELECT parent
FROM yourtable
WHERE item IN (SELECT parent
FROM yourtable
WHERE item IN (SELECT parent
FROM yourtable y2
WHERE item = @ITEM
AND item = y2.item))
UNION ALL
SELECT parent
FROM yourtable
WHERE item IN (SELECT parent
FROM yourtable
WHERE item IN (SELECT parent
FROM yourtable
WHERE item IN (SELECT parent
FROM yourtable y2
WHERE item = @ITEM
AND item = y2.item)))
输出
PARENT
8
4
2
1