tags:

views:

220

answers:

0

I'm having some problems with getting NHibernates HQL to behave the way I want.

I have two tables, lets call them X and XLOG. There are multiple XLOG entries

for each X.

X:
 - Id
XLOG:
 - Id
 - X_Id
 - Timestamp

I want to write an HQL query that will produce the latest XLOG entry for each X. In SQL, I could either make a correlated query using ORDER BY DESC and TOP in the WHERE part of my query or INNER JOIN XLOG with itself to produce the desired result.

However, my efforts to write an HQL query for this have failed so far. The only support for TOP I can find is SetMaxResults on the query - but I need to limit the subquery. In addition subqueries are only allowed in the SELECT and WHERE parts of an HQL query, so I cannot INNER JOIn with it.

The following SQL produces the desired result.

SELECT *
FROM 
 (SELECT x.X_ID, MAX(x.Timestamp) as Timestamp 
  FROM XLOG x 
  GROUP BY X_ID) x1 
INNER JOIN XLOG x2 
ON x2.X_ID = x1.X_ID 
AND x2.Timestamp = x1.Timestamp

It strikes me as a pretty common problem, has anyone found a solution to it in HQL?