0

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.

2
  • 1
    take a look at hibernate projections at some point to handle things like this. Also, i'm not sure if HQL will let you do it but you could do a 'count(distinct m.id)' and 'count(distinct p.id)' like in standard sql. Jun 29, 2011 at 20:28
  • Yes, I have to spend some more time looking at Projections. Coming a C# LINQ background I'm still trying to wrap my head around the differences in Projections in LINQ versus Hibernate. +1 for the idea
    – BuddyJoe
    Jun 29, 2011 at 21:12

1 Answer 1

4
select u.username,
       (select count(m.id) from Message m where m.user = u) as messageCount,
       (select count(p.id) from Post p where p.user = u) as postCount
from User u
order by messageCount desc

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 messageCount by order by 2.

But, as Michael J. Lee indicates, you may also use a simple join and distinct count, which should be more efficient :

select u.username, count(distinct m.id), count(distinct p.id) from User u 
inner join u.messages m
inner join u.posts p
group by u.username)
order by (count(distinct m.id) desc

Using left joins instead of inner joins will also let you get users without any post or without any message.

2
  • Hmmm. Hit by an issue here that no ORDER BY is generated in the SQL no matter what I use messageCount or 2.
    – BuddyJoe
    Jun 29, 2011 at 22:13
  • Take that back had a typo. The workaround works. +1 and answer.
    – BuddyJoe
    Jun 29, 2011 at 22:54

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.