In a custom blog platform with User(s), Post(s), and Message(s).
I know how to do an HQL query with distinct Users and their Post count. Also distinct Users and their Message count.
But if I combine the two with “inner join” technique I get the same count for Posts and Messages. I understand why this is happening because of the joins. How could I do sub-selects in the HQL to get the two counts as separately but as one trip to the database?
Here is an example of the last HQL query I tried.
select u.username, count(m), count(p) from User as u
inner join u.Messages as m
inner join u.Posts as p
group by u.id
order by count(m) desc
Note: I will be changing the order by based off of an option on a web page.
You might have issues with the order by due to the bug http://opensource.atlassian.com/projects/hibernate/browse/HHH-892 which is supposed to be fixed, but doesn’t seem to be in my version of Hibernate. If it’s the case, replace
order by messageCountbyorder by 2.But, as Michael J. Lee indicates, you may also use a simple join and distinct count, which should be more efficient :
Using left joins instead of inner joins will also let you get users without any post or without any message.