I am trying to run a query to select the article that have the most comments related to the article id.
i have a article table and a comments table the comments table has a article_id field that links them and i am trying to do a left join here is want i have so far.
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
i am using CodeIgniter and the above is the output from my active record which is below.
$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();
Ok this works i seem to be getting the correct output but i dont get the number of comments as a value which i need to work from.
so i want to get
article with id 1
has 23 comments
article with id 2
has 3 comments
etc etc
at the moment i am getting a sum of the article ids i think i have a total field with really high values which are not correct can some help with this???
Thanks
SORRY ANSWERED MY OWN QUESTION IM USING SUM AND NOT COUNT AARRRRRGGGGHHHH this works
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
Here is the answer..
SELECT articles.*, count(
comments.article_id) AS total1FROM
articlesJOINcommentsONcomments.article_id=articles.article_idGROUP BY
articles.article_idORDER BYtotal1asc