【问题标题】:Two table join Postgres count child rows两个表连接 Postgres 计数子行
【发布时间】:2023-01-10 15:42:29
【问题描述】:

我有两个表:帖子和回复。

post 表包含这些列

postid | forumName | title | content

回复表包含这些列

replyid | content | postid

我想要一个连接这两个表并为每个论坛返回的 sql 查询

forumName | Total Number of Posts | Total Number of Replies

这很难,因为这两个表是使用 postId 链接的。

select forum, count(id) as postsNum
from posts
group by forum
order by postsNum desc

【问题讨论】:

    标签: sql postgresql


    【解决方案1】:

    你在找这个吗:

    select p.forum
          ,count(distinct id) as posts
          ,count(r.replyid) as replies
    from posts p
    inner join replices r
        on p.[postid] = r.postid
    group by p.forum
    

    【讨论】:

      猜你喜欢
      • 2019-07-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-12
      • 1970-01-01
      • 2011-04-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多