7

我想做类似的事情

{
    SELECT ?page, "A" AS ?type WHERE 
    {
         ?s rdfs:label "Microsoft"@en;
            foaf:page ?page
    }
}
UNION
{
    SELECT ?page, "B" AS ?type WHERE 
    {
         ?s rdfs:label "Apple"@en;
            foaf:page ?page
    }
}

但这会产生语法错误。如何在 SPARQL 中合并两个选择查询?

4

2 回答 2

13

你可以像这样联合它们:

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT * WHERE
{ 
{
    SELECT ?page ("A" AS ?type) WHERE 
    {
         ?s rdfs:label "Microsoft"@en;
            foaf:page ?page
    }
}
UNION
{
    SELECT ?page ("B" AS ?type) WHERE 
    {
         ?s rdfs:label "Apple"@en;
            foaf:page ?page
    }
}
}

(检查SPARQL 验证器

但是,对于这种情况,我认为您根本不需要子查询。例如:

PREFIX rdfs: <http://www.w3.org/2000/01/rdf-schema#>
PREFIX foaf: <http://xmlns.com/foaf/0.1/>

SELECT ?page ?type WHERE
{
    ?s foaf:page ?page .
    { ?s rdfs:label "Microsoft"@en . BIND ("A" as ?type) }
    UNION
    { ?s rdfs:label "Apple"@en . BIND ("B" as ?type) }
}
于 2012-05-29T11:22:17.707 回答
6

根据@user205512 的回答,这是适用于 Virtuoso 的答案:

SELECT * {
    ?s foaf:page ?page .
    {
        SELECT ?page ("A" AS ?type) {
            ?s rdfs:label "Microsoft"@en;
               foaf:page ?page
        }
    } UNION {
        SELECT ?page ("B" AS ?type) {
            ?s rdfs:label "Apple"@en;
               foaf:page ?page
        }
    }
}

诀窍就是?s foaf:page ?pageUNION. 这显然是多余的,但它似乎避免了 Virtuoso 错误,这显然是当你有一个“裸”UNION的子查询时引起的。

于 2012-05-29T18:07:23.233 回答