简体   繁体   English

在HQL中对具有多个列的子查询执行内部联接?

[英]Perform Inner Join on a subquery that has more than one column, in HQL?

I'm trying to join a table with the result of a sub-query (Sub-query returns the result with 3 columns) in HQL but I'm getting a syntax error org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token . 我正在尝试使用HQL中的子查询结果将表与子查询(子查询返回具有3列的结果)连接在一起,但出现语法错误org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token

It looks like INNER JOIN doesn't work in HQL like it does in SQL, so I looked at https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-subqueries but it didn't help. 看起来INNER JOIN无法像在SQL中那样在HQL中工作,所以我查看了https://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-subqueries但这没有帮助。

HQL Query HQL查询

SELECT R
FROM Table R
INNER JOIN (
   SELECT T.id.col1, T.id.col2, MAX(T.col3) max_num
   FROM Table T
   GROUP BY T.id.col1
) b ON R.id.col1 = b.id.col1 AND R.col3 = b.max_num
WHERE R.id.col3 = :param
GROUP BY R.id.col1
ORDER BY R.col3 DESC

Actual Result 实际结果

org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 81

Expected Result 预期结果

Unique Rows that contain the max value of T.col3. 包含T.col3最大值的唯一行。

Note: SQL version of the above query works fine. 注意:以上查询的SQL版本工作正常。

you have not used any aggregate function so no need group by 您没有使用任何聚合函数,因此不需要分组依据

SELECT R.*
    FROM Table R
    INNER JOIN (
       SELECT T.id.col1, T.id.col2, MAX(T.col3) max_num
       FROM Table T
       GROUP BY T.id.col1,T.id.col2
    ) b ON R.id.col1 = b.id.col1 AND R.col3 = b.max_num
    WHERE R.id.col3 = :param

    ORDER BY R.col3 DESC

I would write your HQL query as this: 我会这样写您的HQL查询:

from R as r
where r.id.col3 = :param and r.col3 = (select max(t.col3) from Table t where t.r = r)

This assumes that the T entity has a reference to the R entity called r . 假定T实体引用了称为rR实体。 If not, then change the above code accordingly. 如果不是,则相应地更改上面的代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM