Skip to content
Advertisement

How to correctly use COUNT() when multiple joins are used?

I have the following schema: enter image description here

Multiple webinar entities can have multiple categories hence the webinarcategorymapping table.

What I need to achieve is find the most popular webinars (by likes number) of a specific category.

For doing this, I’ve written the query below:

Due to the many-to-many relationship between category and webinar I’ve decided to join all categories for every webinar into a comma-separated value by using string_agg. This way I’ll be able to perform the search by category by using ilike %search_term%.

In the like table the likeabletype must be equal to webinar and the likeableid filed is the id of an entity on which the like is made. So, in my case, when querying the like table I need to use likeabletype='webinar' and likeableid = webinar.id conditions.

The problem is that is gives me incorrect likes_count results (I guess it’s due to multiple joins that duplicate many rows).

However using count(distinct "like".likeableid) doesn’t help as it just gives me 1 for every row.


What should I change in my query in order to get correct result from count() of likes?

Advertisement

Answer

What I need to achieve is find the most popular webinars (by likes number) of a specific category.

You can aggregate the likes in a subquery and just filter on the categories:

User contributions licensed under: CC BY-SA
6 People found this is helpful
Advertisement