需要帮助在 JPQL 中编写一个没有子查询的查询

Need help to write a query in JPQL, without subqueries

我需要在单个数据库上执行一个简单的查询,但由于 JPQL 中缺少子查询(HAVING 和 EXITS 子句除外),我不知道如何编写。

table 看起来像这样

id  |  eventType | occurenceDate   | comment | data | ...
-----------------------------------------------------------
1   |  event-A   | 2020-09-14      | ...
2   |  event-B   | 2020-09-09      | ...
3   |  event-A   | 2020-09-13      | ...
4   |  event-A   | 2020-09-10      | ...
5   |  event-B   | 2020-09-20      | ...
6   |  event-C   | 2020-09-11      | ...

我需要一个查询来按类型获取在给定参考日期发生的所有下一个事件。 例如,如果参考日期是“2020-09-12”,我希望查询 return id=3 和 5

的实体

获取 eventType/occurenceDate 个元组列表(这是一个唯一的复合键)没问题

SELECT t.type, min(t.occurenceDate) 
FROM table t
WHERE t.occurenceDate > :referenceDate
GROUP BY t.eventType 

但是没有子查询,我不知道如何获取完整的实体。

有什么帮助吗? 谢谢

实际上,子查询是您在 JPQL 中通常处理此查询的方式:

SELECT t1
FROM table t1
WHERE t.occurenceDate > :referenceDate AND
      t.occurrenceDate = (SELECT MIN(t2.occurrenceDate)
                          FROM table t2
                          WHERE t2.eventType = t1.eventType);

在大多数数据库上,如果没有正式的子查询,真的没有办法获得完整的记录(SQL服务器可能是一个例外,但即使在那里你仍然必须使用原生的非 JPQL 查询) .

好的。 只需稍微更改您建议的查询,它就会起作用! 不知道有可能(或认为)在子查询中注入 t1 记录。 (是的,我的数据库知识很少^^)

SELECT t1
FROM table t1
WHERE t1.occurrenceDate = (
    SELECT MIN(t2.occurrenceDate)
    FROM table t2
    WHERE t2.eventType = t1.eventType 
    AND t2.occurenceDate > :referenceDate
);

非常感谢