我想写与QueryOver这样的查询,这样的结果SQL将类似于以下内容:NHibernate的QueryOver HAVING子句
Select Bar, count(*) from Foo group by Bar having count(*) > 1
我该怎么办呢?
我想写与QueryOver这样的查询,这样的结果SQL将类似于以下内容:NHibernate的QueryOver HAVING子句
Select Bar, count(*) from Foo group by Bar having count(*) > 1
我该怎么办呢?
我想你只想用Where方法
Session.QueryOver<Foo>()
.Select(Projections.GroupProperty(Projections.Property<Foo>(foo => foo.Bar)),
Projections.Count<Foo>(f => f.Id))
.Where(Restrictions.Gt(Projections.Count<Foo>(f => f.Id), 1));
从瓦迪姆的答案是正确的,只是想提一提,它可能是一个挑战,如果一个需要检查“具有”状态对另一数据库领域。
例如以下SQL:
select Foo.Bar, COUNT(*) from Foo
group by Foo.Bar
having Foo.Bar <> COUNT(*)
应与QueryOver基本上被创建这样的:
Session.QueryOver<Foo>()
.Select(Projections.GroupProperty(Projections.Property<Foo>(foo => foo.Bar)),
Projections.Count<Foo>(f => f.Id))
.Where(Restrictions.NotEqProperty(Projections.Count<Foo>(f => f.Id), Projections.Property<Foo>(foo => foo.Bar)));
但不幸的NHibernate产生以下无效 SQL(使用,其中,代替具有) :
select Foo.Bar, COUNT(*) from Foo
group by Foo.Bar
where Foo.Bar <> COUNT(*)
为了克服这个问题,我不得不创建以下的传承:
public class NonEqPropertyExpression : EqPropertyExpression
{
public NonEqPropertyExpression(IProjection lhsProjection, IProjection rhsProjection)
: base(lhsProjection, rhsProjection)
{
}
protected override string Op
{
get { return "<>"; }
}
}
和使用,而不是标准NonEqProperty我的新类:
Session.QueryOver<Foo>()
.Select(Projections.GroupProperty(Projections.Property<Foo>(foo => foo.Bar)),
Projections.Count<Foo>(f => f.Id))
.Where(new NonEqPropertyExpression(Projections.Count<Foo>(f => f.Id), Projections.Property<Foo>(foo => foo.Bar)));
在这种情况下产生的SQL是正确的。
我有类似的问题张贴在问题。没有得到另一个数据库,但标准出现在哪里,而不是有。你可以请看看http://stackoverflow.com/questions/29565783/nhibernate-queryover-criteria-appearing-in-where-instead-in-having-clause-err – Ammad 2015-04-10 16:36:36
应该是'Projections.GroupProperty(Projections.Property(foo => foo.Bar))' –
2011-06-15 15:02:36
@David,你就是这样,改了。 – Vadim 2011-06-15 15:36:23
如果我们使用Projections.Sum(),这里有什么区别? – Ammad 2015-04-10 16:31:40