【问题标题】:How to calculate aggregate on inner join如何计算内部连接的聚合
【发布时间】:2020-08-10 22:49:09
【问题描述】:

我有两张表,Post & Comment。帖子表包含有关帖子的信息,评论表包含有关每个帖子的 cmets 数据。下面是结构,

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 以及评论表中每个帖子的 cmets 总数(使用聚合函数计数),并希望数据像这样显示。

Post_ID   Post_Title   Total_Comments
1         ABC           4 
2         XYZ           5
3         123           3

将通过计算特定 post_id 的所有行从 cmets 表中获取总 cmets。

我设法编写了一个内部连接查询,但不知道如何以及在何处放置聚合函数“count”以获取所有 cmets 的总数。以下是我的查询,

select post.post_id, post.post_title, comment.comment_id from post INNER JOIN comment on 
post.post_id = comment.fk_post_id ;

谢谢。

【问题讨论】:

    标签: jquery mysql sql join inner-join


    【解决方案1】:

    你快到了。只需在查询中添加一个GROUP BY 子句,列出来自post 表的列,然后使用count() 计算属于每个组的记录数。

    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
    

    请注意,我在查询中添加了表别名,以缩短读写时间。

    您也可以为此使用子查询,这样可以避免外部聚合:

    select 
        p.*,
        (select count(*) from comment c where p.post_id = c.fk_post_id) no_comments
    from post
    

    【讨论】:

      【解决方案2】:
      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
      

      我强烈建议阅读aggregate functions.

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-06-28
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-12
        • 1970-01-01
        相关资源
        最近更新 更多