Search code examples
javamysqlsqlhibernatehql

Subselect in LEFT JOIN hql


I have a query that uses a subselect in a LEFT JOIN clause of my query every time I run the query it gives the org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( error. with the '(' being the opening parenthesis of my subselect.

my query looks something along the way of:

SELECT a, b, c
FROM table1 as t1
INNER JOIN t1.table2 as t2
INNER JOIN t1.table3 as t3
INNER JOIN t3.table4 as t4
LEFT JOIN ( //<- this one gives the error
    SELECT d, e, f
    FROM table9 as t9
    ....
) as xx WITH xx.prop = t2.prop and xx.prop2 = t4.prop
WHERE t1.yy = true and t1.zz = '0'
GROUP BY t2.column

I have the same query in sql and when I run it in MySQL workbench it works and returns the data that I need. When I use the HQL version it gives an error on the ( that opens my subquery.

Is this kind of subquery possible in HQL or should I use SQL for it?

And if so what did I do wrong?

EDIT: I tried changing the WITH to ON and it still gives the same error.

The inner joins work fine, since this is HQL with a configuration in Java that automatches foreign keys so I don't need an on/witch clause on every join.

EDIT2:

if I comment the left join the query works, so it's not the lack of on or the use of withinstead of it that is causing me trouble


Solution

  • When you join with that table, you need to use the ON keyword.

       LEFT JOIN ( 
            SELECT d, e, f
            FROM table9 as t9
            ....
        ) as xx ON xx.prop = t2.prop and xx.prop2 = t4.prop
    

    Also you forgot the = in the join of the second property.

    EDIT:

    A subquery must be surrounded by parentheses (often by an SQL aggregate function call). Even correlated subqueries (subqueries that refer to an alias in the outer query) are allowed. Note that HQL subqueries can occur only in the select or where clauses.

    From this, you cannot have a sub-query in the from clause.