【问题标题】:Joining three tables with 2 count function使用 2 个计数功能连接三个表
【发布时间】:2021-01-26 00:18:15
【问题描述】:

我已经研究了一天,并无法真正弄清楚。我正在制作一个用户可以发帖,其他用户可以回复和点赞的页面。

我有这三个表:帖子、回复和喜欢。仅供参考,它们都有不同的行数,请参阅下面的完整详细信息。

帖子表

post_id   message
-------   -------
1         This is post #1
2         This is post #2
3         This is post #3

回复表

reply_id  post_id   message
-------   -------   -------
1         1        This is a reply to post #1
2         1        This is a reply to post #1
3         2        This is a reply to post #2
4         2        This is a reply to post #2
5         3        This is a reply to post #3

赞表

like_id   post_id   liked
-------   -------   -------
1         1         Yes
2         1         Yes
3         1         Yes
4         2         Yes
5         2         Yes
6         3         Yes
7         3         Yes

这些是我的表格的结构。我需要实现的如下:

所有表已加入并统计

post_id   total_replies   total_likes
-------   -------------   -----------
1         2               3     
2         2               2
3         1               2    

基本上,对于第一个帖子,它应该显示它有 2 个回复和 3 个喜欢。我似乎无法使用两个计数来做到这一点。它给了我错误的数字。

select posts.post_id, count(replies.post_id) as total_replies, count(likes.post_id) as total_likes from posts
inner join replies on posts.post_id = replies.post_id
inner join likes on posts.post_id = likes.post_id
group by posts.post_id

【问题讨论】:

    标签: mysql sql join count


    【解决方案1】:

    我会建议相关的子查询:

    select p.post_id,
           (select count(*)
            from replies r
            where r.post_id = p.post_id
           ) as total_replies,
           (select count(*)
            from likes l
            where l.post_id = p.post_id
           ) as total_likes
    from posts p;
    

    您的查询的问题在于您要加入两个不同的维度,因此您得到的是笛卡尔积——给定帖子的所有喜欢和所有回复。

    这不仅解决了这个问题,而且在replies(post_id)likes(post_id) 上的索引应该比任何对所有数据进行聚合的解决方案具有更好的性能。

    【讨论】:

      【解决方案2】:

      我接受了您的查询并进行了小修改,以便它产生所需的输出。但是请注意,查询效率不高。 Gordon 的解决方案在效率方面更加有效。

      select 
           posts.post_id,
           count(distinct replies.reply_id) as total_replies,
           count(distinct likes.like_id) as total_likes 
      from posts
       inner join replies on posts.post_id = replies.post_id
       inner join likes on posts.post_id = likes.post_id
      group by 
        posts.post_id;
      

      或者最好预先汇总您的指标。这样会更有效率。

      select 
           posts.post_id,
           r.total_replies,
           L.total_likes 
      from posts
       inner join (Select post_id, count(reply_id) as total_replies from replies group by post_id) r on posts.post_id = r.post_id
       inner join (Select post_id, count(like_id) as total_likes from likes group by posts_id) L on posts.post_id = L.post_id;
      

      需要注意的是,您不会收到不喜欢或不回复的帖子,因为您正在进行内部联接。要获取所有帖子,无论是否喜欢或回复,您必须左键加入。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-11-23
        • 1970-01-01
        • 1970-01-01
        • 2018-11-07
        • 2011-04-12
        相关资源
        最近更新 更多