Mysql查询文章相关评论数

标签 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 的总和,我认为我有一个具有非常高值但不正确的总字段,可以对此提供帮助吗???

谢谢

很抱歉回答了我自己的问题,我使用的是 SUM 而不是计数 AARRRRRGGGGHHHH 这有效

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

最佳答案

答案在这里..

SELECT articles.*, count(comments.article_id) 总计 1 从 articlescomments 上加入 commentsarticle_id = articlesarticle_id GROUP BY articlesarticle_id ORDER BY total1 asc

关于Mysql查询文章相关评论数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13471352/

相关文章:

mysql - 无法在查询中获得正确的记录 - php mysql

mysql - 在MySQL中选择查询多个表

c++ - 在 Windows 中加入等效项

mysql - 如何总结日期和时间?

sql - 如何编写高效的 MySQL 查询以根据约束删除特定行

mysql - 站点层次结构的邻接列表模型,如何按此特定顺序检索所有页面?

javascript - 使用 Mysql 在 CodeIgniter 中使用 Jquery 获取选中框输入值

mysql - 在where子句中设置一个数组

mysql - 数据库和应用程序 : (Very) Many tables or Much redundancy

php - PHP (CodeIgniter) 文件下载中的空行