Mysql查询与文章相关的评论数量

时间:2012-11-20 10:35:32

标签: mysql codeigniter join count sum

我正在尝试运行查询以选择与文章ID相关的评论最多的文章。

我有一个文章表和一个评论表,评论表有一个链接他们的article_id字段,我想在这里做一个左连接是希望我到目前为止。

SELECT *, SUM(`comments`.`article_id`) AS total FROM (`articles`) JOIN `comments` ON `comments`.`article_id` = `articles`.`id` GROUP BY `comments`.`article_id` ORDER BY `total` asc

我正在使用CodeIgniter,以上是我的活动记录的输出,如下所示。

$this->db->select('*');
        $this->db->from('articles');
        $this->db->join('comments', 'comments.article_id = articles.id');
        $this->db->group_by('comments.article_id');
        $this->db->select_sum('comments.article_id', 'total');
        $this->db->order_by('total', 'asc'); 
        $query = $this->db->get();
        return $query->result();

好的,这似乎是我得到正确的输出,但我没有得到评论的数量作为我需要工作的价值。

所以我想得到

id为1的文章 有23条评论

ID为2的文章 有3条评论

等等

目前我正在得到文章ID的总和,我认为我有一个非常高的值的总字段,这是不正确的可以一些帮助吗?

由于

抱怨我自己的问题,使用和而不是计算AARRRRGGGGHHHH这是有效的

SELECT *, COUNT(`comments`.`article_id`) AS total FROM (`articles`) JOIN `comments` ON `comments`.`article_id` = `articles`.`id` GROUP BY `comments`.`article_id` ORDER BY `total` asc

2 个答案:

答案 0 :(得分:1)

以下是答案..

选择文章。*,计数(commentsarticle_id)AS total1 从 articles加入comments commentsarticle_id = articlesarticle_id GROUP BY articlesarticle_id ORDER BY total1 asc

答案 1 :(得分:0)

这是因为您在查询中正在处理文章ID的总和。您需要计算评论总和。删除sum函数中的文章ID,如此SUM(comments.comments_column_name)。我的意思是您在哪个列中为评论表中的每个ID保存评论。