3

我有以下域映射:

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);

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

谢谢,哈雷尔

4

1 回答 1

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));

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

于 2011-04-09T18:57:14.457 回答