2014-05-06 55 views
0

我有一個表(在MySQL)這樣的:選擇傳遞關係的

subject | predicate | object 
A  | P1  | X 
X  | P2  | B 

我想通過使用此表就知道傳遞關係,所以結果應該是這樣的:

element1 | predicate1 | pivot | predicate2 | element2 
A  | P1   | X  | P2   | B 

我已經嘗試了通過使用嵌套查詢構造查詢,但是最後我有語法錯誤(我認爲p2(在嵌套查詢)不能在主查詢來確定)

select p1.subject, p1.predicate, p1.object, p2.predicate, p2.object 
from some_relation p1 
where p1.subject = 'A' 
and p1.object = (select p2.subject from some_relation p2 where p2.object = 'B'); 

任何人都知道如何做這種查詢?可能嗎?

回答

1

使用self join

SELECT 
a.subject as element1, 
a.predicate as predicate2, 
a.object as pivot, 
b.predicate as predicate2, 
b.subject as element2 FROM 
table a JOIN 
table b ON a.object = b.subject; 
+0

我選擇你的答案作爲接受的答案,因爲參考鏈接!謝謝你所有的答案。 –

1

我會寫一個簡單的JOIN

select p1.subject, p1.predicate, p1.object, p2.predicate, p2.object 
from some_relation p1 
inner join some_relation p2 on p1.object = p2.subject and p2.object = 'B' 
where p1.subject = 'A' 

還是你的意思是不同的東西?

1

你不得不加入表本身:

select p1.subject, p1.predicate, p1.object, p2.predicate, p2.object 
from some_relation p1 inner join some_relation p1 
    on p1.object = p2.subject 
where p1.subject = 'A'; 

請注意,你不能這樣做下去。例如,上述查詢只能返回一個「跳」。如果你有一個傳遞鏈,在普通的SQL中很難做到。