Search code examples
sparqlrdfsemantic-web

SPARQL - how to do a join operation


I have a model, where I have 3 classes:

  1. SR - <http://data.sample.com/vocab/StudentRecord>
  2. HCVR - <http://data.sample.com/vocab/HealthCenterVisitRecord>
  3. CR - <http://data.sample.com/vocab/ClassRoom>

StudentRecord has a property classRoom.

HealthCenterVisitRecord has a property studentRecord.

Given a particular ClassRoom URI, how do I find all the StudentRecords, who are properties of HealthCenterVisitRecords.

Query that I tried (The initial part of the query fetches the student belonging to a ClassRoom, but the second part is screwed up and I know it):

SELECT ?hcvr
WHERE {
  ?sr rdf:type <http://data.sample.com/vocab/StudentRecord>.
  ?sr <http://data.sample.com/vocab/classRoom> <http://data.sample.com/resource/ClassRoom/1156>.
  ?sr <http://data.sample.com/vocab/healthCentreVisitRecord> ?hcvr.
}

Another query I tried:

SELECT DISTINCT ?sr WHERE {
  {
  ?sr rdf:type <http://data.sample.com/vocab/StudentRecord>.
  ?sr <http://data.latize.com/vocab/classRoom> <http://data.latize.com/resource/ClassRoom/1156>.
  }
UNION
  { 
        ?hcvr rdf:type <http://data.sample.com/vocab/HealthCentreVisitRecord>.
        ?hcvr <http://data.sample.com/vocab/studentRecord> ?sr.
    }
}
LIMIT 1000

Solution

  • Figured it out, here is the query:

    SELECT ?hcvr
    WHERE {
      ?sr rdf:type <http://data.sample.com/vocab/StudentRecord>.
      ?sr <http://data.sample.com/vocab/classRoom> <http://data.sample.com/resource/ClassRoom/1156>.
      ?hcvr rdf:type <http://data.sample.com/vocab/healthCentreVisitRecord>.
      ?hcvr <http://data.sample.com/vocab/studentRecord> ?sr.
    }