7

我正在尝试编写一个 jpql 查询来选择评论最多的用户。如果两个用户的评论数量相同,我想同时选择两者。

我试过这个,像这样:

SELECT
  c.user, COUNT(c.id) as commentCount 
FROM 
  Comment c
WHERE
  commentCount = (SELECT MAX(SIZE(user.comments)) FROM User user)
GROUP BY 
  c.user

和这个:

SELECT
  c.user
FROM 
  Comment c
GROUP BY 
  c.user
HAVING
  COUNT(c) = (SELECT MAX(SIZE(user.comments)) FROM User user)

这两种方法都不起作用。我需要在这里做什么?

4

3 回答 3

6

这是一个解决方案:

SELECT
  u
FROM 
  User u
WHERE
  u.comments.size = (SELECT MAX(u2.comments.size) FROM User u2)
于 2014-03-27T21:23:18.763 回答
0

如果您使用的是 Oracle,这应该可以工作:

select u from User u where size(u.comments) = (
    select max(count(c.id)) 
    from User u2 inner join u2.comments c 
    group by u2.id
)

max(count(c.id))但在这种情况下,MySQL 和 SQL Server 不支持嵌套聚合函数。建议使用子查询,但使用 HQL,您不能在 from 子句中包含子查询。所以我建议您手动执行此操作,即加载所有用户:

select u, size(u.comments)
from User u

并遍历列表。

于 2013-04-11T22:39:03.710 回答
0

For any others coming here and wanting to select a max(count()) in jpql and doesn't have an array, (like in the question the comments) take following jpql code into consideration:

select e.city 
from Employees e
group by e.city 
having count(e.id) >= All(select count(e) from Employees  e group by e.city)

full example in a JPA Repository:

@Query(value = "select e.city from Employees e group by e.city " +
        "having count(e.id) >= All(select count(e) from Employees  e group by e.city)")
public List<Cities> findCityByMaxEmployeeCount();
于 2021-10-15T16:09:34.333 回答