我有一个表(在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');
任何人都知道如何进行此类查询?可能吗?
答案 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 :(得分: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;
答案 2 :(得分: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';
请注意,您无法无限期地执行此操作。例如,上述查询只能返回一个" hop"。如果你有一个传递链,那么在普通的SQL中很难做到这一点。