我有以下域映射:
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的
答案 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));
因此加入相关子查询的方法是使用别名“外部”查询。