2014-12-09 66 views
0

說我有這樣的一個表:在SQL尋找無限的關係

Child | Parent 

,並把相同的數據,用數字來識別每個孩子家長像這樣:

Child | Parent 
--------------- 
1  2 
2  1 
3  4 
5  4 

第2行形成一種無限的關係,因爲在2中是1的父親,但1也是2的父親,所以它在搜索父親時是永無止境的循環。 我如何在SQL中查找具有這種關係的所有行? 我想我必須使用

START WITH and CONNECT BY 

,但不能完全制定出查詢運行,任何幫助將不勝感激!

+0

向我們展示你迄今爲止寫的東西。 (即使任何不起作用的東西) – nop77svk 2014-12-09 13:10:40

回答

0

對同一張表的簡單內連接是否不能滿足您的需求?

SELECT table1.Parent as Row, table1.Child as OtherRow 
FROM table table1 
    inner join table table2 
    ON table1.Parent = table2.Child 
    AND table1.Child = table2.Parent 

這會給你的「父 - >子」行的每場比賽,像這樣:

Row | OtherRow 
----|---------- 
    1 | 2 

但你可以使用結果作爲一個子查詢拔出所有行

SELECT table.Parent as Parent, table.Child as Child 
FROM table 
    INNER JOIN (that query) query 
    ON (table.Parent = query.Row AND table.Child = query.OtherRow) 
     OR (table.Parent = query.OtherRow AND table.Child = query.Row) 

這將使你

Parent | Child 
-------|------ 
    1 | 2 
    2 | 1