简体   繁体   中英

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,

Post Table
post_id (Primary Key), post_title, post_description

Comment Table
comment_id (Primary Key), comment_text, fk_post_id (Foreign Key)

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.

Post_ID   Post_Title   Total_Comments
1         ABC           4 
2         XYZ           5
3         123           3

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,

select post.post_id, post.post_title, comment.comment_id from post INNER JOIN comment on 
post.post_id = comment.fk_post_id ;

Thanks.

SELECT post.post_id
,post.post_title
,COUNT(comment.comment_id) as Total_coments 
FROM post 
INNER JOIN comment on  post.post_id = comment.fk_post_id 
GROUP BY post.post_id, post.post_title

I would strongly suggest reading about aggregate functions.

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.

select 
    p.post_id, 
    p.post_title, 
    count(*) no_comments
from post p
inner join comment c on p.post_id = c.fk_post_id
group by p.post_id

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:

select 
    p.*,
    (select count(*) from comment c where p.post_id = c.fk_post_id) no_comments
from post

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM