I’m building my query using the advice from Does ORMLITE support SQL EXISTS?
public List<Crag> getAllCragsWithLocation() {
QueryBuilder<Crag, Integer> cragQueryBuilder = _helper.getCragDao().queryBuilder();
QueryBuilder<CragLocation, Integer> cragLocationQueryBuilder = _helper.getCragLocationDao().queryBuilder();
try {
cragLocationQueryBuilder.where().eq("locationType", 0);
cragQueryBuilder.where().exists(cragLocationQueryBuilder);
return cragQueryBuilder.query();
} catch (Exception e) {
Log.e(TAG,e.toString());
return new ArrayList<Crag>();
}
}
This returns all crags regardless of if they have a cragLocation so long as there are any cragLocation with a locationType of 0. Which is understandable…
In the example linked above…
QueryBuilder<Visit, Integer> visitQb = visitDao.queryBuilder();
visitQb.where().eq(Visit.CLIENT_ID_FIELD, client.getId());
QueryBuilder<Client, Integer> clientQb = clientDao.queryBuilder();
clientQb.where().exists(visitQb);
List<Client> results = clientQb.query();
I guess the query is linking to the id of a specific client or perhaps more clearly
select * from client c
where EXISTS (select * from visit v where c._id = v.client_id)
in my case
select * from Crag c
where EXISTS (select * from CragLocation cl where c.id = cl.crag_id)
So my final query would be:
select * from Crag c
where EXISTS (select * from CragLocation cl where c.id = cl.crag_id and cl.location_type = 0)
I don’t think you want to be using SQL EXISTS here. The query that ORMLite is going to generate does not include any special
WHEREclause — it’s not that smart.This query means that if the there are any locations where
locationType == 0then it will return all of theCragentries.I would recommend that you use the
where().in(QueryBuilder)method. This way you can return the crags that have a location whose type is 0.This will generate a SQL query something like: