简体   繁体   中英

(JPQL) - Query for getting user with highest number of records

Excuse me for anking again about this issue but I need to have a JPA query for this:

select username, count(*)
from Records
group by username
order by count(*) desc
limit 1

I thought about smth like:

select r.username,count(*) from Records r order by r.username desc

and then to call

getResultList().get(0)

but I am allowed to write only:

select r from Records r order by r.username desc

and in this case I do not know how to get what I need. Does anyone have any idea?

The SQL query has a group by, and orders by count. The JPA query doesn't have any group by and orders by user name. So I don't see how they could return the same thing.

The equivalent JPQL query is

select r.username, count(r.id)
from Record r
group by r.username
order by count(r.id) desc

If you call setMaxResults(1) on the Query object, the limit clause will be added to the generated SQL query, making it completely equivalent.

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