I want to transform the SQL statement
SELECT * FROM (SELECT * FROM `votes` ORDER BY `date` DESC) AS sub GROUP BY `username`
into JPQL. The idea is to get the latest vote (ORDER BY date
DESC) for each user (GROUP BY username
).
I understand that JPQL does not support subqueries in FROM, so I tried "IN"
# does not work!
SELECT v FROM Vote v WHERE v.id IN (SELECT tmp.id FROM Vote tmp ORDER BY date DESC) GROUP BY v.username
but that gives me the first entries. Then I tried "MAX"
# does not work!
SELECT v FROM Vote v WHERE v.date IN (SELECT MAX(tmp.date) FROM Vote tmp GROUP BY tmp.username)
as well, but this gives me multiple entries of the same user as date
is not unique...
EDIT:
I thought of creating a VIEW from the SQL syntax as a workaround, but as the JPQL query refers to the class (not the table) this didn't get me far ;-)
EDIT:
Then I thought of JOINs and that lead me to Native Queries. Turns out I can use the above SQL with nativeQuery = true
:
@Query(value = "SELECT * FROM (SELECT * FROM `votes` ORDER BY `date` DESC) AS sub GROUP BY `username`", nativeQuery = true)
And that works!