【问题标题】:JPQL greatest-n-per-group queryJPQL best-n-per-group 查询
【发布时间】:2017-06-12 03:35:08
【问题描述】:

有没有办法使用 JPQL 编写这个查询:

select *
from "tbCita" c inner join "tbAccionCita" ac1
on c."citaId" = ac1."citaId"
left outer join "tbAccionCita" ac2 on ( c."citaId" = ac2."citaId" and
    (ac1."fechaAccionCita" < ac2."fechaAccionCita" 
     or ac1."fechaAccionCita" = ac1."fechaAccionCita" 
     and ac1."accionCitaId" < ac2."accionCitaId")
 )
 inner join "tbUsuarioCita" uc 
    on c."citaId" = uc."citaId"
  inner join "tbUser" u 
    on uc."userId" = u."userId"
 where 
    ac2."accionCitaId" is null
    and u."userId" = 1

fechaAccionCita 是一个日期 :)

我正在尝试获取 userId = 1 的所有约会 (tbCita) 的最新状态(一个约会有多个状态)。

查询按预期工作,但在 JPQL 中它给了我以下错误:

with-clause 引用了两个不同的 from-clause 元素

这里是查询:

SELECT c "
        + "FROM Cita c "
        + "INNER JOIN c.usuarioCita u "
        + "INNER JOIN FETCH c.accionCita a "
        + "LEFT OUTER JOIN c.accionCita a2 on (a.fechaAccionCita < a2.fechaAccionCita or "
        + "a.fechaAccionCita = a2.fechaAccionCita and a.accionCitaId < a2.accionCitaId) "

【问题讨论】:

  • 不相关,但是:有更有效的方法可以连接到表中的“最新”行。你的实际上是效率最低的。 (顺便说一句:您是否也为所有 Java 类加上 Cls 前缀 - 就像您对数据库中的表一样?)

标签: java spring postgresql jpa


【解决方案1】:

以下是否有效?另外,您确定 OR 语句中的逻辑按预期工作吗?看来您可能需要一组额外的括号。

select c
from tbCita c, tbAccionCita ac1, tbUsuarioCita uc, tbUser u 
left join tbAccionCita ac2 on (
    c.citaId = ac2.citaId 
    and (ac1.fechaAccionCita < ac2.fechaAccionCita 
        or ac1.fechaAccionCita = ac1.fechaAccionCita 
        and ac1.accionCitaId < ac2.accionCitaId))
where c.citaId = ac1.citaId
    and c.citaId = uc.citaId
    and uc.userId = u.userId
    and ac2.accionCitaId is null
    and u.userId = 1

【讨论】:

    猜你喜欢
    • 2013-09-05
    • 2019-03-06
    • 1970-01-01
    • 2011-01-07
    • 1970-01-01
    • 1970-01-01
    • 2021-02-14
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多