错误:列“this_.created_time”必须出现在GROUP BY子句中或用于聚合函数

时间:2016-10-25 10:44:12

标签: java sql postgresql hibernate

当我使用hibernate的标准进行查询时遇到了问题。生成的SQL非常简单:

/* criteria query */ 
select
    count(*) as y0_ 
from
    cx_vss_video this_ 
where
    this_.uploader_id=? 
order by
    this_.created_time asc

它抱怨错误:

    Caused by: org.postgresql.util.PSQLException: ERROR: column "this_.created_time" must appear in the GROUP BY clause or be used in an aggregate function
  Position: 105
        at org.postgresql.core.v3.QueryExecutorImpl.receiveErrorResponse(QueryExecutorImpl.java:2157)

存在一个存在的问题here。但它的答案似乎非常复杂而且不合理。那么还有其他解决方案吗?

我的实体类:

@Entity
@Table(name = "cx_vss_video")
public class Video {

    public enum TranscodingStatus {
      NOT_START, TRANSCODING, SUCCESS, ERROR, CANCELED;
    }

    @Id
    @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "cx_vss_video_seq")
    @SequenceGenerator(name = "cx_vss_video_seq", sequenceName = "cx_vss_video_seq")
    private Long id;

    @Column(name = "uploader_name", nullable = false)
    private String uploaderName;

    @Column(name = "file_name")
    @NaturalId
    private String fileName;

    @Column(name = "created_time")
    private Date createdTime = new Date();

    @Column(name = "transcoding_status")
    @Enumerated(EnumType.STRING)
    private TranscodingStatus transcodingStatus = TranscodingStatus.TRANSCODING;
}

我可以按file_name正常订购,但在created_time订购时没有运气。我很困惑问题出在哪里?当我使用H2时,问题也会出现。

修改 我终于通过删除order参数来解决问题,现在它可以正常工作。

CriteriaImpl criteriaImpl = criteria instanceof CriteriaImpl ? (CriteriaImpl) criteria : null;
  if (criteriaImpl != null) {
    Iterator<OrderEntry> it = criteriaImpl.iterateOrderings();
    while (it.hasNext()) {
      it.next();
      it.remove();
    }
    criteria.setProjection(Projections.rowCount());
    totalResults = (long) criteria.uniqueResult();
  }

1 个答案:

答案 0 :(得分:0)

您需要在查询上使用聚合函数。所以,它应该是这样的:

select count(*) as y0_ 
from cx_vss_video this_ 
where this_.uploader_id = ? 
group by ??
order by max(this_.created_time) asc;

也就是说,您需要group by并修复order by

为什么呢?那么,你的原始查询 - 没有group by - 是一个返回一行的聚合查询。订购一行结果集没有意义。所以,我假设您希望通过某种方式进行聚合,因此??。然后,您可以通过聚合列或聚合函数进行排序。