我试图在QueryDSL中编写一个查询来获取由其parentId分组的表中最旧的元素.
SQL等价物应该是:
SELECT a.* FROM child a
INNER JOIN
(
SELECT parentId, MAX(revision) FROM child GROUP BY parentId
) b
ON (
a.parentId = b.parentId AND a.revision = b.revision
)
现在在QueryDSL中,我坚持使用语法.
JPQLQuery subquery = JPAExpressions
.select(child.parent, child.revision.max())
.from(child)
.groupBy(child.parent);
HibernateQuery query = new HibernateQuery<>(session);
query.from(child)
.where(child.parent.eq(subquery.???).and(child.revision.eq(subquery.???))));
如何使用子查询编写此查询?
表格看起来像这样:
___parent___ (not used in this query, but exists)
parentId
P1 | *
P2 | *
P3 | *
___child___
parentId | revision
P1 | 1 | *
P1 | 2 | *
P1 | 3 | *
P2 | 2 | *
P2 | 3 | *
P3 | 1 | *
___result from child, the highest revision for each parentId___
P1 | 3 | *
P2 | 3 | *
P3 | 1 | *
到目前为止我尝试过的:
.where(JPAExpressions.select(child.parent,child.revision).eq(subquery));
-> org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected end of subtree
和许多语法错误……
我现在使用脏循环,因为我还没有找到解决方案.