我有两个表,Post&Comment。帖子表包含有关帖子的信息,评论表包含有关每个帖子的评论数据。下面是结构,
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,并从评论表中获取每个帖子的评论总数(使用汇总函数计数),并希望这样显示数据。
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
您几乎在那里:
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