I have three tables: class
, student
, and teacher
table class
{
class_id(PK)
}
table student
{
student_id(PK)
class_id(PK+FK)
}
table teacher
{
teacher_id(PK)
class_id(PK+FK)
}
I have a query in SQL, which works fine.
SELECT data.class_id, count(data.class_id) AS count
FROM ((SELECT class_id FROM student)
union all
(SELECT class_id FROM teacher)) AS data
GROUP BY data.user_id
ORDER BY count desc
The query contains sub query in the from clause and union operation. I unable to convert it to the HQL.
please give me the efficient HQL query from the above SQL query.
Sub queries in the from clause are supported by most of the SQL implementations. The correlation variables from the relations in from clause cannot be used in the sub-queries in the from clause.
A Subquery or Inner query or a Nested query is a query within another SQL query and embedded within the WHERE clause. A subquery is used to return data that will be used in the main query as a condition to further restrict the data to be retrieved.
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.
where(criteriaBuilder.in(path). value(subquery)); TypedQuery<Object> typedQuery = entityManager. createQuery(select); List<Object> resultList = typedQuery. getResultList();
Unfortunately HQL does not support UNION queries. Two alternative strategies to solve your problem are:
Or Inheritance mapping. Particularly Table per concrete class strategy with an abstract Person
superclass inherited both by Student
and Teacher
seems to fit your problem well:
select p.id, count(c)
from Person p join p.classes c
group by p.id
order by count(c) desc
You cannot place a subquery at the from
clause in HQL. Only select
or where
clauses.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With