具有元组条件的QueryDSL和SubQuery [英] QueryDSL and SubQuery with Tuple condition

查看:1149
本文介绍了具有元组条件的QueryDSL和SubQuery的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试在QueryDSL中编写一个查询来获取按其parentId分组的表中最旧的元素。

I am trying to write a query in QueryDSL to fetch the oldest elements of a table grouped by their parentId.

SQL等价物应该是:

The SQL equivalent should be:

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中,我遇到了语法问题。

Now in QueryDSL I'm stuck with the syntax.

JPQLQuery<Tuple> subquery = JPAExpressions
                .select(child.parent, child.revision.max())
                .from(child)
                .groupBy(child.parent);

HibernateQuery<Child> query = new HibernateQuery<>(session);
query.from(child)
    .where(child.parent.eq(subquery.???).and(child.revision.eq(subquery.???))));

如何使用子查询编写此查询?

How do you write this query using a 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

和许多语法错误。 ..

and many syntax errors ...

我现在使用脏循环,因为我还没有找到解决方案。

I use a dirty loop, for now, since I haven't found a solution yet.

推荐答案

您可以使用 Expressions.list()为in子句指定多个列:

You can use Expressions.list() to specify more than one column for the in clause:

query.from(child).where(Expressions.list(child.parent, child.revision).in(subquery));

另一种方法是使用 innerJoin() ,就像你原来的SQL一样。

The alternative is to use innerJoin(), as in your original SQL.

这篇关于具有元组条件的QueryDSL和SubQuery的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆