嵌套选择带标准的计数查询

时间:2010-07-06 16:20:21

标签: nhibernate count criteria

说我们有2个实体EntityA和EntityB,以及相关的表,TableA和TableB。

我必须实现此查询:

select a.Id , (select count(b.Id) from TableB b where b.FKa = a.Id and b.AnotherField > 0) as TheCount
from TableA a 
自从我写这段代码以来,我非常接近:

var subCrit = DetachedCriteria.For<EntityB>
                                        .Add<EntityB>(e => e.AnotherField > 0)
                                        .SetProjection(LambdaProjection.Count<EntityB>(e => e.Id).As("TheCount"));

var crit = Session.CreateCriteria<EntityA>
                        .SetProjection(LambdaProjection.GroupProperty<EntityA>(e => e.Id).As("Id),
                                            Projections.SubQuery(subCrit));

如果我执行此条件,我将获得以下SQL:

select a.Id as Id , (select count(b.Id) from TableB b where b.AnotherField > 0) as TheCount from TableA a

正如你所看到的,它非常接近我正在努力实现的......问题(这是一个很大的问题:D) 是子查询和TableA的实体之间没有链接(其中b.FKa = a.Id)。 我找不到通过条件将子查询与外部查询相关联的方法。

有什么建议吗?

很多

的Alessandro

修改

改变观点我也可以这样做:

 var crit = Session.CreateCriteria<EntityA>()
                   .CreateAlias<EntityB>(a => a.B, () => b);
                   .SetProjection(LambdaProjection.Count<A>(a => b.Id).As("TheCount"),
                   .SetProjection(LambdaProjection.GroupProperty<EntityA>(a => a.Id));

这是生成以下sql:

select count(b.Id) as TheCount, a.Id as IDa
from TableA a left outer join TableB b
on a.Id = b.FKa
group by a.Id

但是在这里你可以看到附加的where子句b.AnotherField&gt; 0缺少,我不知道如何插入它只是为了计数。

希望很清楚,再次感谢

2 个答案:

答案 0 :(得分:3)

以下是解决方案:

var condition = Expression.Gt("b.AnotherField",0);
var conditionalProjection = Projections.Conditional(condition, Projections.Constant(1), Projections.Constant(0));

crit = Session.CreateCriteria<EntityA>()
                   .CreateAlias<EntityB>(a => a.B, () => b);
                   .SetProjection(Projections.Count(conditionalProjection).As("TheCount"),
                     (LambdaProjection.GroupProperty<EntityA>(a => a.Id));

这是生成的SQL:

选择计数(案例b.AnotherField&gt; 0然后1,否则0结束)作为TheCount,a.Id 来自TableA的内连接TableB b

希望它有用

欢呼声

的Alessandro

enter code here

答案 1 :(得分:0)

我的建议是更改SQL语句

选择a.is,count(a.id) 来自TableA a JOIN TableB b ON a.id = b.fka AND b.af&gt; 0 GROUP by a.ID

为它创建简单的标准。