You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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;

语句说明

  1. 使用LEFT JOIN关联两张表,确保无回复的论坛也能被统计(总回复数显示为0)
  2. COUNT(DISTINCT p.postid)统计每个论坛的帖子总数,避免因关联回复表导致的重复计数
  3. COUNT(r.replyid)统计总回复数,LEFT JOIN中无回复的帖子对应replyid为NULL,不会被计入统计
  4. 按论坛名称分组,最终按总帖子数降序排序

修正你原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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.05 11:05:20