2009-12-09 76 views
0

在每個員工存儲多行的表中,我想爲每個員工提供一行代表每個員工的最新條目。下面是我在哪裏用手寫SQL:NHibernate +加入派生表

SELECT [all the selected columns here] 
FROM Nominations t 
    inner join 
    (select max(NominationId) mostRecentNominationId, 
     EmployeeId from Nominations group by EmployeeId) n 
     on n.mostRecentNominationId = t_.NominationId 

從源數據是這樣的:

nomination_id  employee_id 
------------------------------- 
1     5 
2     5 
4     10 
7     10 

這會給我這樣的事情:

nomination_id  employee_id 
------------------------------- 
2     5 
7     10 

我沒有已經能夠弄清楚如何通過NHibernate ICriteria來完成這種類型的查詢。有什麼想法嗎?

+0

什麼是您的映射是什麼樣子? – 2009-12-09 15:03:13

回答

2

以下是你需要做什麼:

DetachedCriteria dCriteria = DetachedCriteria.For<Nomination>("nomination") 
     .SetProjection(Projections.Max("nomination.Id")) 
     .Add(Restrictions.EqProperty("nomination.EmployeeId", "employee.Id")); 

var nominations = Session.CreateCriteria<Nomination>("nom") 
      .CreateCriteria("Employee", "employee") 
      .Add(Subqueries.PropertyEq("nom.Id", dCriteria)).List<Nomination>(); 

這不是equilevant在問題providfed的SQL查詢,但它究竟是做同樣的事情。

由上述標準查詢生成的SQL查詢是:

SELECT * 
FROM Nomination nom 
inner join Employee employee on nom.EmployeeId=employee.EmployeeId 
WHERE nom.NominationId = 
(SELECT max(nomination.NominationId) as maxID 
    FROM Nomination nomination 
    WHERE nomination.EmployeeId = employee.EmployeeId)