如果您使用的是Oracle 11.2或更高版本,則使用Oracle的CONNECT BY聲明優先使用CTE(公用表表達式)。
WITH
aset -- Create pseudo table with ID2 as ID1 and vice versa
AS
(SELECT id1, id2
FROM (SELECT id1, id2
FROM foo
UNION
SELECT id2, id1
FROM foo)
WHERE id1 < id2),
bset (id1, id2) -- Extract hierarchy from pseudo table
AS
(SELECT id1, id2
FROM aset
WHERE id1 = 1
UNION ALL
SELECT aset.id1, aset.id2
FROM bset INNER JOIN aset ON bset.id2 = aset.id1
WHERE bset.id1 <> aset.id2)
SELECT DISTINCT bset.id2 -- Only keep values that were originally ID2
FROM bset INNER JOIN foo ON bset.id2 = foo.id2
ORDER BY id2;
下面是使用CONNECT你能不能約你期望看到更清晰的同樣的事情BY
WITH
aset
-- Create pseudo table with ID2 as ID1 and vice versa
AS
(SELECT id1, id2
FROM (SELECT id1, id2
FROM foo
UNION
SELECT id2, id1
FROM foo)
WHERE id1 < id2),
bset
-- Extract hierarchy from pseudo table
AS
( SELECT id2
FROM aset
START WITH id1 = 1
CONNECT BY PRIOR id2 = id1)
SELECT DISTINCT bset.id2
-- Only keep values that were originally ID2
FROM bset INNER JOIN foo ON bset.id2 = foo.id2
ORDER BY id2
?你的樹只有最高等級1。在你的查詢中,你從ID1 = 1開始,在你的數據中沒有辦法從那裏到ID2 = 5。您的數據需要一行ID1 = 2,ID2 = 5。或者ID1 = 1,ID2 = 4。或者你可以擺脫「用id1 = 1開始」來顯示你的整個樹 - 但仍然只有1級,所以'connect by'什麼都不做。 – kfinity
請發佈查詢的預期輸出。你也可以在(1,4)中使用'START WITH id1',即從沒有父節點的所有ID1開始 - 這將在選擇表中的所有行時結束。 –
'select distinct id2' does does yield the records 2,3,5。問題是什麼? –