SPARQL:如何将变量传递给子查询?

SPARQL: How do you pass a variable into a subquery?

这个有效:

SELECT ?propLabel ?val WHERE {
    BIND("incoming"@en AS ?propLabel)
    {
      SELECT (COUNT(?s) AS ?val) WHERE {
        ?s ?p wd:Q8740.
        _:b72 wikibase:directClaim ?p.
      }
    }
}

但这不是,我假设是因为首先评估子查询,因此 ?entity 尚未绑定:

SELECT ?propLabel ?val WHERE {
  BIND(wd:Q8740 as ?entity)
    BIND("incoming"@en AS ?propLabel)
    {
      SELECT (COUNT(?s) AS ?val) WHERE {
        ?s ?p ?entity.
        _:b72 wikibase:directClaim ?p.
      }
    }
}

如果是这样,我们如何"pass"一个变量到子查询中?

阅读 SPARQL Bottom Up Semantics 文章中的 Blazegraph 中的优化 部分,然后稍微帮助优化器:

SELECT ?propLabel ?val WHERE {
  BIND (wd:Q8740 AS ?entity)
  BIND("incoming"@en AS ?propLabel)
  { 
    SELECT (COUNT(?s) AS ?val) ?entity WHERE {
      ?s ?p ?entity .
      [] wikibase:directClaim ?p 
    } GROUP BY ?entity
  } 
}

Try it!

只需将 ?entity 变量添加到投影中(然后您应该 GROUP BY ?entity 显式)。
因此,您将在 query plan.

中有额外的 joinVars=[entity]

有趣的是,使用 hint:Query hint:optimizer "None" 无法禁用此类优化。