【问题标题】:Select distinct with group by and having in HQL在 HQL 中使用 group by 和 have 选择 distinct
【发布时间】:2016-01-03 10:11:50
【问题描述】:

在我的 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 个实体是链接的,那么你必须使用内连接,目前你正在使用叉积,这可能会降低你的性能。第二次尝试指定 latitude , longitude 属性来自哪个实体,如果它们来自 AirbnbProperty 然后 ap.latitude >=:minLat

标签: java sql hibernate hql


【解决方案1】:

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

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

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
  )

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-05-23
    • 2021-03-19
    • 2011-03-27
    • 2016-03-08
    • 1970-01-01
    • 2011-04-21
    相关资源
    最近更新 更多