I have a table “Table” similar to this one:
id user_id owner_id due_date
------+------------+-------------+--------------------------
1 | 1 | 1 | 2011-07-26 12:28:50
2 | 1 | 1 | 2011-07-26 15:32:11
3 | 1 | 1 | 2011-07-27 08:11:58
4 | 2 | 1 | 2011-07-26 15:19:44
5 | 2 | 1 | 2011-07-23 12:00:50
As you can see, a user identified by FK user_id can have multiple entries with different due_date.
I would like to fetch all most recent Table entities grouped by user_id.
In plain MySQL, it could look like this:
SELECT * FROM (
SELECT * FROM TABLE
WHERE owner_id = xxx
ORDER BY due_date DESC
) AS sorted
GROUP BY user_id
I would first select with ORDER BY, then apply a GROUP BY (all in one SELECT doesn’t work, unfortunately. see e.g. here http://www.cafewebmaster.com/mysql-order-sort-group).
Now I would like to implement this as HQL (with Grails). The problem is that HQL does not support inner SELECT’s in the FROM part, so the following approach won’t work:
def findMostRecentPerUser( Owner owner ) {
def result = Table.executeQuery("""
from Table as t1
where t1.id in (
select sorted.id from (select * from Table as t2 where t2.owner_id = ${owner.id} order by t2.due_date desc) as sorted group by sorted.user_id
)
""")
return result
}
Another way would be a Criteria but I’ve no idea how to implement it that way.
Could someone point me into the right direction? Your help is greatly appreciated.
This way should work. Improvements appreciated.