PostgreSQL中关联posts与replies表统计各论坛帖子及回复数
关联posts和replies表统计论坛数据的SQL解决方案
需求说明
编写SQL查询关联posts与replies表,返回每个论坛的以下统计数据:forumName | Total Number of Posts | Total Number of Replies
表结构
- posts表字段:
postid|forumName|title|content - replies表字段:
replyid|content|postid
最终SQL查询语句
SELECT p.forumName, COUNT(DISTINCT p.postid) AS `Total Number of Posts`, COUNT(r.replyid) AS `Total Number of Replies` FROM posts p LEFT JOIN replies r ON p.postid = r.postid GROUP BY p.forumName ORDER BY `Total Number of Posts` DESC;
语句说明
- 使用
LEFT JOIN关联两张表,确保无回复的论坛也能被统计(总回复数显示为0) COUNT(DISTINCT p.postid)统计每个论坛的帖子总数,避免因关联回复表导致的重复计数COUNT(r.replyid)统计总回复数,LEFT JOIN中无回复的帖子对应replyid为NULL,不会被计入统计- 按论坛名称分组,最终按总帖子数降序排序
修正你原SQL的问题
你提供的基础帖子统计SQL存在字段名不匹配问题:
原SQL:
select forum, count(id) as postsNum from posts group by forum order by postsNum desc
- posts表无
forum字段,应改为forumName - posts表无
id字段,应改为postid
修正后的基础帖子统计SQL:
SELECT forumName, COUNT(postid) AS postsNum FROM posts GROUP BY forumName ORDER BY postsNum DESC;
内容的提问来源于stack exchange,提问作者sharmapn
相关产品推荐
相关产品推荐

