[英]“could not extract ResultSet” in JPQL GROUP BY query
In my Spring Boot 1.5 application with Spring Data JPA, I have a TDR
table like: 在带有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
where I need to find the last records grouped by m_id
and p_id
. 在这里我需要找到按m_id
和p_id
分组的最后一条记录。 With PostgreSQL SQL, I do this with the MAX
aggregate function: 使用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
which returns the correct records: 返回正确的记录:
Table TDR
-----------------------
id | c_id | m_id | p_id
4 | 2 | 1 | 2
5 | 3 | 1 | 1
Since the GROUP BY
does not include c_id
, the SQL is structured as correlated sub-query and matched with a join (see this question for details). 由于GROUP BY
不包含c_id
,因此SQL被构造为相关子查询并与联接匹配(有关详细信息,请参阅此问题 )。
I'd like to convert this SQL to JPQL with this Lombok @Data
entity: 我想使用以下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;
}
but my JPQL for the correlated sub-query with parameterized m ID ( :m_id
): 但是我的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
)
results in this error: 导致此错误:
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
The thing that jumps out to me is that your first SELECT: 让我惊讶的是您的第一个SELECT:
SELECT FROM
...doesn't state which columns you're selecting ...没有说明您要选择的列
Select just the join column in the correlated sub-query: 在相关子查询中仅选择联接列:
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
)
The ObjectDB GROUP BY article was helpful as was this question . ObjectDB GROUP BY文章对此问题很有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.