如何计算mysql中每个帖子的用户数和注释数?

时间:2016-08-28 16:29:23

标签: mysql database

这是我的评论表:

   |id(int) | user_id(int) | post_id(int) | text(char)|
   ----------------------------------------------------
   |        |              |              |           |

我想计算有多少用户对每篇帖子都有评论 每个帖子都有多少评论。

我已经完成了后者:

select count(*) from comments group by post_id;

但第一个怎么样?任何的想法?

3 个答案:

答案 0 :(得分:2)

有多少帖子存在?

select count(1) from posts

每个用户评论了多少帖子?

select user_id, count(distinct post_id)
from comments
group by user_id

用户评论过每个帖子吗?

select user_id
from comments
group by user_id
having count(distinct post_id) = (select count(1) from posts)

有多少用户评论了每个帖子?

select count(1)
from (
    select user_id
    from comments
    group by user_id
    having count(distinct post_id) = (select count(1) from posts)
) sub

答案 1 :(得分:1)

编辑回答

有多少用户对每篇帖子发表了评论

select post_id, count(distinct user_id) as users_count
from comments
group by post_id

原始回答

有多少用户对每篇帖子都有评论

我没有看到你的帖子表,所以我认为它存在。

select count(*) AS users_with_comments_to_every_post
from (
  select count(distinct post_id) as count_comments
  from comments
  group by user_id
  ) c
inner join ( select count(*) AS count_posts from posts ) p on 
  c.count_comments = p.count_posts 

我们需要posts表来处理没有评论的帖子。

每篇帖子都有多少条评论

select post_id, count(*)
from comments
group by post_id

答案 2 :(得分:0)

有多少用户对每篇帖子都有评论

SELECT post_id, count(distinct user_id) as user_count 
FROM comments
GROUP BY post_id

这样就可以避免子查询。