【问题标题】:JPQL select query, unable to Group ByJPQL 选择查询,无法分组
【发布时间】:2020-08-27 07:53:56
【问题描述】:

下班后我似乎没有找到实现这一目标的方法,我有 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;

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】:

    您看到的错误源于您不清楚每个分销商组需要哪个实体。这是使用 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 实体是否是每个分销商的最新实体。

    【讨论】:

    • 这就像魔术一样!我还有一个问题,有时我会为同一个经销商得到 2 个价格,因为一个是 Diesel,另一个是 Blue Diesel。在这种情况下,我只是按价格选择,我是在 java 中修改返回列表还是有办法编辑查询?
    • 使用 HQL 很难实现(尽管在一般 SQL 中很容易)。这听起来更像是一个后续问题。
    猜你喜欢
    • 2017-08-14
    • 2014-03-22
    • 2013-10-23
    • 2017-11-17
    • 2015-10-02
    • 2011-01-17
    • 2020-11-28
    • 2016-07-08
    • 2016-03-29
    相关资源
    最近更新 更多