在循环中选择COUNT

时间:2014-01-05 07:56:05

标签: php jquery mysql mysqli count

我有两张桌子:'新闻'和'评论'。如何计算每篇新闻文章的评论数量?

SELECT `news`.`name`,`news`.`text` (SELECT COUNT(1) FROM `comments` WHERE
 `comments`.`news_id`=`news`.`id`) AS `comments` FROM  `news`,`comments`

这不行。

1 个答案:

答案 0 :(得分:1)

以这种方式试试

SELECT n.name, n.text, COUNT(c.news_id) total_comments
  FROM news n LEFT JOIN comments c 
    ON n.id = c.news_id
 GROUP BY n.id

这是 SQLFiddle 演示