我正在使用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>();
}
}
这将返回所有 crags,无论它们是否具有 cragLocation,只要存在 locationType 为 0 的 cragLocation。这是可以理解的......
在上面链接的示例中...
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();
我猜查询链接到特定客户的 id 或者更清楚
select * from client c
where EXISTS (select * from visit v where c._id = v.client_id)
就我而言
select * from Crag c
where EXISTS (select * from CragLocation cl where c.id = cl.crag_id)
所以我的最终查询是:
select * from Crag c
where EXISTS (select * from CragLocation cl where c.id = cl.crag_id and cl.location_type = 0)