[英]NHibernate criteria query using Max() projection
我必须使用NHibernate实现这样的事情
DetachedCriteria maxDateQuery = DetachedCriteria.forClass(FtpStatus.class);
ProjectionList proj = Projections.projectionList();
proj.add(Projections.max("datetime"));
proj.add(Projections.groupProperty("connectionid"));
maxDateQuery.setProjection(proj);
Criteria crit = s.createCriteria(FtpStatus.class);
crit.add(Subqueries.propertiesEq(new String[] {"datetime", "connectionid"}, maxDateQuery));
List<FtpStatus> dtlList = crit.list();
(此代码段来自Hibernate条件查询,该查询使用键字段上的Max()投影并按外键主键进行分组 )
我的问题是Nhibernate没有实现在此行中使用的“ Subqueries.propertiesEq”:
crit.add(Subqueries.propertiesEq(new String[] {"datetime", "connectionid"}, maxDateQuery));
您能建议一种解决方法吗?
答案是(谈论NHibernate )使用EXISTS
而不是IN
。 查询看起来像这样
// the below outer query, has essential feature
// ALIAS name "outer"
// and this is used here, in the "subquery"
var maxDateQuery = DetachedCriteria.For<MyEntity>("myEntity")
.SetProjection(
Projections.ProjectionList()
.Add(Projections.GroupProperty("MyId"))
.Add(Projections.Max("MyDate"))
)
.Add(Restrictions.EqProperty(
Projections.Max("MyDate"),
Projections.Property("outer.MyDate")) // compare inner MAX with outer current
)
.Add(Restrictions.EqProperty("MyId", "outer.MyId")) // inner and outer must fit
;
// here ... the "outer" is essential, because it is used in the subquery
var list = session.CreateCriteria<Contact>("outer")
.Add(Subqueries.Exists(maxDateQuery))
... // e.g. paging
.List<MyEntity>();
这将创建如下查询:
FROM [MyEntityTable] outer
WHERE exists
(
SELECT myEntity.MyId
, max(myEntity.MyDate)
FROM [MyEntityTable] myEntity
WHERE myEntity.MyId = outer.MyId // matching ID
GROUP BY myEntity.MyId
HAVING max(myEntity.MyDate) = outer.MyDate // matching max and current date
)
可以在QueryOver
语法中找到相同类型的查询(甚至更复杂) :
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.