简体   繁体   中英

JPQL with subquery to select max count

I'm trying to write a jpql query to select the user with the most comments. If two users have the same number of comments I want to select both.

I tried this, something like this:

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

and this:

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

Neither approach works. What do I need to do here?

Here is a solution:

SELECT
  u
FROM 
  User u
WHERE
  u.comments.size = (SELECT MAX(u2.comments.size) FROM User u2)

This should work if you are using 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
)

But MySQL and SQL Server do not support nested aggregate functions, max(count(c.id)) in this case. It is suggested to use a subquery, but with HQL you cannot have subqueries in a from clause. So I suggest you do this manually, ie load all users:

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

and loop through the list.

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();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM