1

我有以下两个表:

帖子

  • post_id
  • 帖子标题
  • post_timestamp

评论

  • comment_id
  • post_post_id
  • 评论内容
  • 评论时间戳

我想创建一个显示每周发帖数和评论数的报告。像这样的东西:

Week    StartDate      Posts     Comments
1       1/1/2012       100        305
2       1/8/2012       115        412

我有这个查询,但它只从 Posts 表中提取。

select makedate( left(yearweek(p.post_timestamp),1),week(p.post_timestamp, 2 ) * 7 ) as Week, COUNT(p.post_id) as Posts  
FROM cl_posts p
GROUP BY Week
ORDER BY WEEK(p.post_timestamp)

我如何也添加评论计数?

4

2 回答 2

3

我认为你需要这样的东西:

select
  week(post_timestamp) as Week,
  adddate(date(post_timestamp), INTERVAL 1-DAYOFWEEK(post_timestamp) DAY) as StartDate,
  count(distinct post_id),
  count(comment_id)
from
  posts left join comments
  on comments.posts_post_id = posts.post_id
group by Week, StartDate
于 2012-12-06T15:06:18.363 回答
0

这是一种方法,使用join

select coalesce(p.week, c.week) as week, p.Posts, c.Comments
from (select makedate( left(yearweek(p.post_timestamp),1),week(p.post_timestamp, 2 ) * 7 ) as Week,   
             COUNT(*) as Posts  
      FROM cl_posts p
      GROUP BY Week
     ) p full outer join
     (select makedate( left(yearweek(c.comment_timestamp),1),week(c.comment_timestamp, 2 ) * 7 ) as Week,   
             COUNT(*) as Comments
      FROM cl_comments c
      GROUP BY Week
     ) c
     on p.week = c.week
order by 1 

我使用 afull outer join而不是另一种连接类型的原因是即使其中一个或其他计数为 0 也能保持数周。我没有将表连接在一起的原因可能是因为您希望在评论日期之前获得报告,而不是与评论关联的帖子的发布日期。

于 2012-12-06T15:08:12.803 回答