NHibernate查询比较两个子查询

时间:2011-07-03 18:29:22

标签: nhibernate queryover

如何将两个子查询与带有WithSubQuery的查询结合起来?我想要下面的内容(确切的语法无关紧要):

 query.WithSubquery.WhereValue(QueryOver.Of<Child>()
                                  .Where(m => m.Parent.Id == paretAlias.Id)
                                  .Select(Projections.Max("SomeProp")))
                                  .Lt(QueryOver.Of<Child>(() => childAlias)
                                  .Where(m => childAlias.Id == parentAlias.Id)
                                  .Select(Projections.Max("SomeOtherProp")));

我看不到任何允许我比较两种方法的WithSubquery方法。它有

其中:采取lambda

WhereProperty:将属性与子查询进行比较

WhereValue:将值与子查询进行比较

WhereExists:接受查询。

基本上我想要一个带有子查询并与另一个子查询进行比较的方法

sql中的示例输出查询将是:

 select * from Parent inner join child on parent.id = child.parentid where 
     (select max(SomeProp) from child where child.parentid = parent.id) >   (select max(SomeOtherProp) from child where child.parentid = parent.id)

1 个答案:

答案 0 :(得分:1)

我认为您应该可以通过稍微修改sql-query

来解决您的问题
SELECT p.* FROM [Parent] as p
WHERE EXISTS
(
    SELECT c.[parentId] as parentid FROM [Child] as c
    WHERE c.[parentid] = p.[id]
    GROUP BY c.[parentid] 
    HAVING MAX(c.[someProp]) < MAX(c.[someOtherProp])
)

如果这返回了正确的结果集,那么您可以使用QueryOver实现它,如下所示:

Parent p = null;
Child c = null;

var subquery = QueryOver.Of(() => c)
    .SelectList(list => list.SelectGroup(() => c.ParentId))
    .Where(Restrictions.LtProperty(
        Projections.Max(() => c.SomeProp), 
        Projections.Max(() => c.SomeOtherProp)))
    .And(Restrictions.EqProperty(
        Projections.Property(() => c.ParentId), 
        Projections.Property(() => p.Id)));

var query = QueryOver.Of(() => p)
    .WithSubquery.WhereExists(subquery);

IList<Parent> resutl = Session.CreateQuery(query);

我已经回答了类似的问题,上面的查询还有一个Criteria API版本:

Selecting on Sub Queries in NHibernate with Critieria API

我希望这会有所帮助,欢呼!