我必须使用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 criteria query using Max() projection on key field and group by foreign primary key)
我的问题是Nhibernate没有实现此行中使用的“Subqueries.propertiesEq”:
crit.add(Subqueries.propertiesEq(new String[] {"datetime", "connectionid"}, maxDateQuery));
你能建议一个解决方法吗?
答案 0 :(得分:0)
这里的答案是(谈论 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
语法中相同类型的查询(甚至更复杂):