Skip to content
Advertisement

How to calculate aggregate on inner join

I have two tables, Post & Comment. Post table contains info about posts & comment table contains the comments data about each post. Below is there structure,

I need to take post_id, post_title from post table and total no of comments (using aggregate function count) on each post from comment table & want the data to be showed like this.

Total comments will be taken from the comments table by counting all the rows of a specific post_id.

I have managed to write a inner join query but dont know how and where to put aggregate function “count” to get total of all comments. Below is my query,

Thanks.

Advertisement

Answer

You are almost there. Just add a GROUP BY clause to your query that lists columns coming from the post table, and use count() to count how many records belong to each group.

Note that I added table aliases to the query, to make it shorter to read and write.

You could also use a subquery for this, which avoids the need for outer aggregation:

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