msyql查询返回受where子句限制的内部连接数

axzmvihb  于 2021-06-20  发布在  Mysql
关注(0)|答案(1)|浏览(278)

我用下面的查询来计算一篇文章发表后30分钟内的评论数量。有两张table, posts 以及 comments 哪些是 INNER JOIN 埃德 posts.id 以及 comments.post_id 像这样:

SELECT id, count(post_id) as num_comm from posts
  INNER JOIN comments on id = post_id
  WHERE (UNIX_TIMESTAMP(posts.time_posted) - UNIX_TIMESTAMP(comments.time_posted)) < (30 * 60)
    AND comments.reply_to_id = 0
  GROUP BY id
  ORDER BY num_comm ASC;

我遇到的问题是,查询返回的是 num_comm 结果,而不仅仅是那些在发帖后30分钟内发表的评论的数量 comments.reply_to_id 设置为0。
如何将查询更改为仅返回满足中条件的注解数 WHERE 条款?

z31licg0

z31licg01#

想必,帖子是在评论之前发布的。所以,你的价值总是负数。尝试:

SELECT id, count(*) as num_comm 
FROM posts p INNER JOIN
     comments c
     ON p.id = c.post_id
WHERE (UNIX_TIMESTAMP(c.time_posted) - UNIX_TIMESTAMP(p.time_posted)) < (30 * 60) AND
      c.reply_to_id = 0
GROUP BY p.id
ORDER BY num_comm ASC;

我不太喜欢转换成unix时间戳。我认为代码更加清晰:

WHERE c.time_posted < p.time_posted + interval 30 minute AND
      c.reply_to_id = 0

相关问题