条件查询ORDER BY产生错误。这是SQL-SERVER的限制吗?如何在复杂的条件查询中正确排序?

时间:2012-04-13 15:22:43

标签: java sql-server hibernate

我有以下条件查询:

    String cat = "H";
    Criteria criteria = currentSession().createCriteria(this.getPersistentClass()).
            add(Restrictions.ne("category", cat)).
            createAlias("employees", "emp").
            createAlias("emp.company", "company");
    Disjunction disjunction = Restrictions.disjunction();
    for(Region r: regions){
           disjunction.add(Restrictions.eq("company.region", r));
    }
    criteria.add(disjunction);

    if(status != null) {
        criteria.add(Restrictions.eq("status", status));
    }

    if (period != null) {
        criteria.add(Restrictions.eq("period", period));
    }

    criteria.setProjection(Projections.groupProperty("id")) //this line was added to try to "fix" the error, but it still happened.
    criteria.addOrder(Order.asc("id"));

我猜一个解释我的标准查询的查询可能是:

  select n.* from NOMINATION n
  join NOMINEE i on n.NOM_ID = i.NOM_ID
  join EMPLOYEE e on e.EMP_ID = i.EMP_ID
  join COMPANY c on c.COMPANY_CODE = e.COMPANY_CODE
  where n.CATEGORY_CODE!='H' and (c.REGION_ID = ? or c.REGION_ID = ? or c.REGION_ID = ?) and n.STATUS_ID = ? and n.PERIOD_ID = ?
  order by n.NOM_ID

我在这里尝试做的事情非常令人困惑,但大多数情况下它都有效,除非我添加此特定行(尽管查询工作正常):

 criteria.addOrder(Order.asc("id"));

然后我收到错误:

 java.sql.SQLException: Column "NOMINATION.NOM_ID" is invalid in the ORDER BY clause because it is not contained in either an aggregate function or the GROUP BY clause.

我怀疑这与SQL-SERVER有关。我已经按id进行分组了。那我在这里做错了什么,或者我应该只使用HQL?

1 个答案:

答案 0 :(得分:1)

您当前的查询似乎是一个简单的查询,它没有使用任何组函数,也没有按查询分组。根据您当前的要求,您不必使用此行。

criteria.setProjection(Projections.groupProperty("id")).addOrder(Order.asc("id"));

或者你必须修改你的sql语句。