如何在选择帖子时计算评论

时间:2011-07-02 06:24:40

标签: mysql sql

我有两张桌子

tb_posts id,title,description

tb_comments id,post_id,comment

我想选择所有评论数量的帖子。

如何为它编写单个查询?

4 个答案:

答案 0 :(得分:2)

我认为应该这样做:

SELECT tb_posts.id, tb_posts.title, tb_posts.description 
    FROM  tb_posts INNER JOIN tb_comments
       ON  tb_posts.id = tb_comments.post_id
GROUP BY tb_posts.id, tb_posts.title, tb_posts.description 
HAVING COUNT(*) > SOME_THRESHOLD_VALUE

答案 1 :(得分:1)

SELECT  a.id,a.title,a.description, count(b.id) FROM tb_posts a, tb_comments b, 
  WHERE a.id=b.post_id;

答案 2 :(得分:0)

试试这个,

SELECT tb_posts.title, COUNT(tb_comments.id)
FROM tb_comments LEFT JOIN tb_posts ON tb_posts.id = tb_comments.post_id
GROUP BY tb_comments.post_id, tb_posts.title

答案 3 :(得分:0)

我得到了解决方案

   SELECT p.id,p.title,p.description,c.cm FROM tb_posts AS p LEFT JOIN    
     (SELECT post_id,count(id) as cm FROM `tb_comments` GROUP BY post_id) AS c
 ON p.id = c.post_id