Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can i inner join a subquery in JPQL

Tags:

jpa

jpql

jpa-2.0

I need a JPQL for the MySQL query:

SELECT * 
FROM table1 t1 
INNER JOIN table2 t2 
  ON t1.id = t2.table1.id 
INNER JOIN (SELECT * FROM table1 t3 
            INNER JOIN table2 t4 ON t3.id = t4.table1.id 
            WHERE t3.name = 'xxx') subTable 
  ON t1.number = subTable.number 
WHERE t1.number = '5' 
  AND id = '3'
like image 610
Rajaa Avatar asked Mar 28 '12 11:03

Rajaa


People also ask

Can we use inner join in JPQL?

JPQL provides an additional type of identification variable, a join variable, which represent a more limited iteration over specified collections of objects. In JPQL, JOIN can only appear in a FROM clause. The INNER keyword is optional (i.e. INNER JOIN is equivalent to JOIN).

Can we use inner join in subquery?

Inner Join will execute sub query only once.

Can we use subquery in JPQL?

A subselect is a query embedded into another query. It's a powerful feature you probably know from SQL. Unfortunately, JPQL supports it only in the WHERE clause and not in the SELECT or FROM clause. Subqueries can return one or multiple records and can use the aliases defined in the outer query.

Can you join a subquery?

A subquery can be used with JOIN operation. In the example below, the subquery actually returns a temporary table which is handled by database server in memory. The temporary table from the subquery is given an alias so that we can refer to it in the outer select statement.


1 Answers

Your query seems quite pathological, perhaps say what result you are trying to query, and include your object model.

In general, JPQL does not support sub-selects in the from clause, so your query is not directly convertable to JPQL.

You can always just execute it as a JPA native SQL query, since you seem to be comfortable with SQL than JPQL.

like image 137
James Avatar answered Oct 15 '22 08:10

James