我正在尝试运行查询以选择与文章 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
从
articles
在 comments
上加入 comments
。article_id
= articles
。article_id
GROUP BY articles
。article_id
ORDER BY total1
asc
关于Mysql查询文章相关评论数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13471352/