I have two persistent classes, Comment and Vote. A Comment can be associated with many Votes and there is a @OneToMany - @ManyToOne relationship between them that's working correctly. What I'm trying to do is to sort the comments by most upvotes. A Vote is an upvote if Vote.up column is 1 and downvote if Vote.up is 0. I'm trying to work out their difference
So far this is my HQL but it's not working
select c from Comment c
order by (
(select count(*) from c.votes v where v.up = 1)
- (select count(*) from c.votes v where v.up = 0)
) desc
Is there a way to do this?
HQL doesn't support such a syntax, so you'll have to use a native query for this: