如何在聚合值上使用相关子查询进行QueryOver?

时间:2011-04-04 15:22:26

标签: nhibernate queryover

我有以下域映射:

Person
------
int PersonId
IList<PersonDetails> Details;

PersonDetails
-------------
Person Owner (mapped by using the FK field, PersonId)
string Name
string Address
DateTime UpdateDate

翻译成类似的表结构:

Person
------
PersonId (int)
Birthday (date)

PersonDetails
-------------
PersonId (FK, integer)
Name (string)
Address (string)
UpdateDate (date)

如何使用QueryOver重新创建以下SQL查询?

SELECT * 
FROM Person p INNER JOIN Details d ON p.PersonId = d.PersonId 
WHERE d.UpdateDate = (SELECT MAX(UpdateDate) 
                      FROM   PersonDetails
                      WHERE  PersonId = p.PersonId);

即,为每个人选择最新的PersonDetails。 我见过一些例子,但它们都没有与使用聚合值的相关子查询相关...

谢谢, Harel的

1 个答案:

答案 0 :(得分:14)

嘿,在努力寻找解决方案之后,以下就是诀窍:

QueryOver.Of<Person>(() => personAlias)
     .Left.JoinAlias(p => p.Details, () => personDetailsAlias)
     .WithSubquery.WhereProperty(() => personDetailsAlias.UpdateDate).Eq(
            QueryOver.Of<PersonDetails>(() => maxPersonDetailsAlias)
                 .Where(ps => maxPersonDetailsAlias.Owner.Id == personAlias.Id)
                 .Select(Projections.Max<PersonDetails>(ps => ps.UpdateDate)))
                     .SelectList(resList => resList.Select(() => personAlias.Id).Select(() => personDetailsAlias.Id));

因此加入相关子查询的方法是使用别名“外部”查询。