JPQL选择查询,无法进行分组

问题描述 投票:1回答:1

小时后,我似乎没有找到实现的方法,我有2个实体。

public class Price{
@Id
int id;

@Temporal(TemporalType.DATE)
private Date dtComu;

private String descCarb;

private Double price;

//bi-directional many-to-one association to Distributor
@ManyToOne
@JoinColumn(name="idImpiant")
private Distributor distributor;

AND

public class Distributor{

@Id
private int idImpiant;

private String province;

//bi-directional many-to-one association to Price
@OneToMany(mappedBy="distributor")
private List<Price> prices;

我需要做的似乎很简单,对于每个分销商,得到最新的价格。我想的是得到一个价格列表(每个价格都有一个分销商),按日期排序,按分销商分组。我的查询是。

SELECT e FROM Price e JOIN e.distributor d WHERE e.descCarb like '%Diesel%' group by e.distributor order by e.dtComu desc

我得到的错误是:

SELECT列表不在GROUP BY子句中,并且包含非聚合列'price0_.id',这在功能上不依赖于GROUP BY子句中的列。

是否有其他我没有想到的方法来实现这个功能?

java mysql jpa jpql
1个回答
1
投票

你所看到的错误是源于你不清楚你想要每个分销商组的哪个实体。 这里有一个使用HQL的方法。

select e FROM Price e JOIN e.distributor d
where e.descCarb like '%Diesel%' and
      e.dtComu = (select max(ee.dtComu) from Price ee where ee.distributor = e.distributor)

它使用一个相关的子查询来检查是否有匹配的信息 Price 实体是每个分销商的最新实体。

© www.soinside.com 2019 - 2024. All rights reserved.