在JPQL GROUP BY查询中“无法提取ResultSet”

时间:2017-03-30 22:59:51

标签: java postgresql jpa spring-data-jpa jpql

在使用Spring Data JPA的Spring Boot 1.5应用程序中,我有一个TDR表,如:

     Table TDR
-----------------------
id | c_id | m_id | p_id
 1 |   1  |    1 |    1
 2 |   1  |    1 |    2
 3 |   2  |    1 |    1
 4 |   2  |    1 |    2
 5 |   3  |    1 |    1

我需要找到按m_idp_id分组的最后记录。使用PostgreSQL SQL,我使用MAX聚合函数执行此操作:

SELECT t.id, t.c_id, t.m_id, t.p_id
FROM (
  SELECT MAX(id) AS id, m_id, p_id 
  FROM tdr
  WHERE m_id = 1                      -- <<< parameterized below
  GROUP BY m_id, p_id
  ) m JOIN tdr t ON t.id = m.id

返回正确的记录:

     Table TDR
-----------------------
id | c_id | m_id | p_id
 4 |   2  |    1 |    2
 5 |   3  |    1 |    1

由于GROUP BY不包含c_id,因此SQL的结构为correlated sub-query并与联接相匹配(有关详细信息,请参阅此question)。

我想使用此Lombok @Data实体将此SQL转换为JPQL:

@Data
@Entity
@Table(name = "TDR")
public class TDR implements Serializable {
    @Id
    @GeneratedValue(strategy = GenerationType.IDENTITY)
    @Column(nullable = false)
    private Long id;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="m_id")
    private M m;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="p_id")
    private P p;

    @ManyToOne(optional=false, cascade = { CascadeType.ALL })
    @JoinColumn(name="c_id")
    private C c;
}   

但我的JPQL用于带参数化m ID(:m_id)的相关子查询:

SELECT t FROM TDR t WHERE t.id in (
  SELECT MAX(t.id) AS id, t.m, t.p FROM TDR t WHERE t.m = :m GROUP BY t.m, t.p
  )

导致此错误:

org.springframework.dao.InvalidDataAccessResourceUsageException: could not extract ResultSet; SQL [n/a]; nested exception is org.hibernate.exception.SQLGrammarException: could not extract ResultSet
   // at ...
Caused by: org.hibernate.exception.SQLGrammarException: could not extract ResultSet
   // at ...
Caused by: org.postgresql.util.PSQLException: ERROR: subquery has too many columns

2 个答案:

答案 0 :(得分:0)

跳出来的东西是你的第一个SELECT:

cPickle

...未说明您选择的列

答案 1 :(得分:0)

仅选择相关子查询中的连接列:

SELECT t FROM TDR t WHERE t.id in (
  SELECT MAX(t.id) FROM TDR t WHERE t.m = :m GROUP BY t.m, t.p
  )

ObjectDB GROUP BY articlequestion一样有用。