在每个员工存储多行的表中,我想为每个员工提取一行,代表每个员工的最新条目。这是我手写SQL的地方:
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 :(得分: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>();
这与问题中提供的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)