jquery - 如何计算内部连接的聚合
问题描述
我有两张表,发布和评论。帖子表包含有关帖子的信息,评论表包含有关每个帖子的评论数据。下面是结构,
Post Table
post_id (Primary Key), post_title, post_description
Comment Table
comment_id (Primary Key), comment_text, fk_post_id (Foreign Key)
我需要从 post 表中获取 post_id、post_title 以及评论表中每个帖子的评论总数(使用聚合函数计数),并希望数据像这样显示。
Post_ID Post_Title Total_Comments
1 ABC 4
2 XYZ 5
3 123 3
通过计算特定 post_id 的所有行,将从评论表中获取总评论。
我设法编写了一个内部连接查询,但不知道如何以及在何处放置聚合函数“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
我强烈建议阅读有关聚合函数的信息。