繁体   English   中英

如何计算内部连接的聚合

[英]How to calculate aggregate on inner join

我有两张表,发布和评论。 帖子表包含有关帖子的信息,评论表包含有关每个帖子的评论数据。 下面是结构,

Post Table
post_id (Primary Key), post_title, post_description

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

我需要从评论表中获取每个帖子的 post_id、post_title 和评论总数(使用汇总的 function 计数),并希望数据像这样显示。

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

通过计算特定 post_id 的所有行,将从评论表中获取总评论。

我设法编写了一个内部连接查询,但不知道如何以及在哪里放置聚合 function “count”以获取所有评论的总数。 以下是我的查询,

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

谢谢。

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

我强烈建议阅读有关聚合函数的信息。

你快到了。 只需在查询中添加一个GROUP BY子句,该子句列出来自post表的列,然后使用count()计算属于每个组的记录数。

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

请注意,我在查询中添加了表别名,以缩短读写时间。

您也可以为此使用子查询,这样就不需要外部聚合:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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