在HQL中使用"Select distinct with group by and having"

3
在我的Java项目中,我需要执行一个HQL查询。
以下是我的HQL查询:
select count(distinct 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 (latitude >=:minLat AND latitude <=:maxLat)" +
            " AND (longitude >=:minLong " + (meridian180WithinDistance ? "OR" : "AND") + " longitude <=:maxLong) AND " +
            "acos(sin(:locationLatitude) * sin(radians(latitude)) + cos(:locationLatitude) * cos(radians(latitude)) * cos(radians(longitude) -:locationLongitude)) <=:R " +
            "GROUP BY ap.neighborhood having count(ap.id) > 19  

这个计数总是会产生一个"1"的结果,然而,如果我删除查询的最后一行,它会返回一个正确的结果,但我需要根据上面的条件限制我的结果。请问有人能帮忙吗?

首先,您应该了解如果这4个实体是链接的,则必须使用内连接,当前您正在使用交叉产品,这可能会降低性能。其次,请尝试从哪个实体指定纬度、经度属性,例如如果它们来自AirbnbProperty,则ap.latitude >=:minLat。 - akash777.sharma
1个回答

2
您只获取到了1,因为您选择了用于分组的不同值的计数(n.id = ap.neighborhood,因此n.idap.neighborhood相同)。
我假设您查询的目的是计算与超过19个AirbnbProperty相关联的不同Neighborhood的数量(当然,在应用所有其他条件之后)。如果是这样,您需要的基本上是这个:
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
  )

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接