3

我越来越习惯用 SPARQL 编写常规查询,但我仍然无法处理更高级的内容。我最新的问题是尝试选择除与 where 子句匹配的内容之外的所有内容。例如,假设我想找到所有喜欢他们妻子不喜欢的汽车颜色的丈夫(我正在研究一个专有模型,所以请原谅这个例子并相信它在真实模型中是有意义的)。

我可能有:

<bob> <spouse> <alice>
<bob> <likes> <red>
<alice> <likes> <red>
<carl> <spouse> <dorothy>
<carl> <likes> <blue>
<dorothy> <likes> <yellow>
<eric> <spouse> <fannie>
<eric> <likes> <black>

选择 carl 和 eric 但不选择 bob 的查询是什么?如果您可以在同一查询中选择蓝色和黑色,则可以加分。选择 bob 很简单:

select ?husband ?color where {?husband <spouse> ?wife . ?husband <likes> ?color . ?wife <likes> ?color}

我正在寻找的是:

select ?husband ?color where {?husband <spouse> ?wife . ?husband <likes> ?color . NOT (?wife <likes> ?color)}

但显然这是错误的。那么什么是对的?

4

2 回答 2

4

我通过其他来源找到的一个正确答案是这样的:

select ?husband ?color where {?husband <spouse> ?wife . ?husband <likes> ?color . OPTIONAL {?wife <likes> ?wifecolor FILTER (?wifecolor = ?color)} FILTER (!BOUND(?wifecolor))}

它至少适用于 eric,但我没有测试过 carl。

于 2008-12-17T19:44:54.413 回答
3

在 SPARQL 1.1 中有一种更简单、更自然的方法(但它相当于 OPTIONAL/BOUND 解决方案):

SELECT ?husband ?color 
WHERE {
    ?husband <spouse> ?wife .
    ?husband <likes> ?color .
    FILTER NOT EXISTS {?wife <likes> ?color}
}
于 2012-04-28T08:05:42.787 回答