选择distinct with group by和HQL

时间:2016-01-03 10:11:50

标签: java sql hibernate hql

在我的java项目中,我需要进行HQL查询 这是我的HQL查询: 选择计数(不同的n.id)" +             " FROM Neighborhood n,NeighborhoodMeta meta,NeighborhoodAffordability aff,AirbnbProperty as ap" +             " WHERE n.id = meta.id AND n.id = aff.id AND n.id = ap.neighborhood AND aff.singleHomeValue!= null" +             " AND(纬度> =:minLat AND latitude< =:maxLat)" +             " AND(经度> =:minLong" +(meridian180WithinDistance?" OR":" AND")+"经度< =:maxLong)AND&#34 ; +             " acos(sin(:locationLatitude)* sin(弧度(纬度))+ cos(:locationLatitude)* cos(弧度(纬度))* cos(弧度(经度) - :locationLongitude))< =:R " +             " GROUP BY ap.neighborhood have count(ap.id)> 19 这个计数总是产生一个" 1"但是,如果我删除了查询的最后一行,它会返回一个正确的结果,但是我需要根据上面的条件限制我的结果。 有人可以帮忙吗?

1 个答案:

答案 0 :(得分:2)

您只获得了1,因为您选择了用于分组的不同值的计数(n.id = ap.neighborhood,因此n.idap.neighborhood相同})。

我假设您的查询的目标是与超过19 Neighborhood s相关联的不同AirbnbProperty的计数(当然,在应用所有其他条件之后)。如果是这样,你需要的基本上是这样的:

select count(*) from
 (select n.id
   from
   ... the rest of your query without group by ...
   group by n.id having count(ap.id) > 19
 )

但是,Hibernate不支持from子句中的子查询,因此您必须使用in运算符解决它:

select count(*) from Neighborhood n
 where n.id in 
  (select n.id
    from
    ... the rest of your query without group by ...
    group by n.id having count(ap.id) > 19
  )
相关问题