I'd like to do something like
{
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
}
}
But this gives a syntax error. How can I union two select queries in SPARQL?
You can union them like this:
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
}
}
}
(check with the SPARQL validator)
However I don't think you need sub queries at all for this case. For example:
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) }
}
Based on @user205512's answer, here's one that works on 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
}
}
}
The trick was just do add an additional ?s foaf:page ?page
triple outside of the UNION
. This is obviously redundant, but it seems to avoid the Virtuoso bug, which is apparently caused when you have a “naked” UNION
with subqueries.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With