简体   繁体   中英

Subquery with Inner Join in HQL

I want to print title from Movies table which has Foreign key Movie_id in Rating table.In rating table we have to get top 10 results based on movie_id occurrence .Since Limit is not allowed in HQL so setMaxResults is used

Query q=session.createQuery("select Title from Movies  as M Inner Join ( SELECT Movie_id, COUNT(*)  FROM Rating  GROUP BY Movie_id ORDER BY COUNT(*) DESC LIMIT 10 ) as R ON M.Movie_id=R.Movie_id").setMaxResults(10);

Exception is:

java.lang.IllegalArgumentException: org.hibernate.hql.internal.ast.QuerySyntaxException: unexpected token: ( near line 1, column 59 [select Title from com.rahul.model.Movies  as M Inner Join ( SELECT Movie_id, COUNT(*)  FROM com.rahul.model.Rating  GROUP BY Movie_id ORDER BY COUNT(*) DESC LIMIT 10 ) as R ON M.Movie_id=R.Movie_id]

Since HQL doesn't support subquery how to achieve it ?

You can write this query as a JOIN / GROUP BY :

select m.Title
from Movies m Inner Join
     Rating r
     on m.Movie_id = r.Movie_id
group by m.Movie_Id, m.Title
order by count(*) desc
limit 10;

解决

Query q=session.createQuery("select m.title from Movies m Inner Join Rating r on m.movie_id = r.movie_id group by m.movie_id, m.title order by count(*) desc").setMaxResults(10);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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