Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

HQL: Is it possible to perform an INNER JOIN on a subquery?

Tags:

sql

hibernate

hql

Diagram

The diagram above is a simplified version of the database structure that I use to log item locations through time. I wrote the following SQL query which returns the current item inventory of each location:

select * 
from ItemLocationLog l
inner join 
(select g.idItemLocationLog, max(g.dateTime) as latest
from ItemLocationLog g
group by g.idItem)
as i 
on l.idItem = i.idItem and l.dateTime = i.latest

The problem I'm having is that I want to convert that to HQL, but I haven't found the syntax to perform an INNER JOIN on a subquery, and it seems like this is not supported. Is there a way to convert the above to HQL (or a Criteria) or will I have to use a standard SQL query in this case? Thanks.

like image 433
JayPea Avatar asked May 16 '12 18:05

JayPea


People also ask

Can we use inner join in subquery?

A subquery can be used with JOIN operation.

Can we use join in HQL query?

HQL Join : HQL supports inner join, left outer join, right outer join and full join. For example, select e.name, a. city from Employee e INNER JOIN e.

Is subquery supported in HQL?

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. Note that subqueries can also utilize row value constructor syntax.

Can you join tables in a subquery?

A subquery is a query that is nested inside a SELECT , INSERT , UPDATE , or DELETE statement, or inside another subquery. Joins and subqueries are both used to combine data from different tables into a single result.


1 Answers

http://docs.jboss.org/hibernate/orm/3.3/reference/en/html/queryhql.html#queryhql-subqueries

Note that HQL subqueries can occur only in the select or where clauses.

You can rewrite the query so that the subquery is part of the where clause instead. Referencing the l.idItem in the subquery

like image 56
Arkaine55 Avatar answered Sep 24 '22 15:09

Arkaine55