5

我想用 QueryOver 编写这样的查询,以便结果 SQL 类似于以下内容:

Select Bar, count(*) from Foo group by Bar having count(*) > 1

我该怎么做 ?

4

2 回答 2

7

我想你只会使用 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));
于 2011-06-15T14:24:38.460 回答
3

Vadim 的回答是正确的,只是想提一下,如果需要针对另一个数据库字段检查“拥有”条件,这可能是一个挑战。

例如以下 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(使用 where 而不是拥有):

    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 是正确的。

于 2012-03-27T21:20:25.960 回答