0

I have two tables:

news ->     
  id_news    
  title    
  body    
  date_created    
  image    
  category_id    

comments ->     
  id_comments    
  news_id    
  body    
  date_created

How can I write query to get all news, count all the comments for every news and present that query in the view part?

1
  • Could you paste the structure of your tables? Commented Dec 3, 2012 at 16:28

3 Answers 3

2
select
      N.ID_News,
      N.Title,
      N.Body,
      N.Date_Created,
      N.Image,
      N.Category_ID,
      count(C.ID_Comments) CommentCount
   from
      News N
         LEFT JOIN Comments C
            on N.ID_News = C.News_ID
   group by 
      N.ID_News
   order by
      whatever column(s) are important to you
Sign up to request clarification or add additional context in comments.

5 Comments

Sorry to keep you waiting. This is working, but I get only one news, not all. I guess this is because only one news has comments at this time or it doesn't matter?
It does not matter, @DRapp is using LEFT JOIN
@m4t1t0 what could be the problem then? (After the query I have this part $q = $this->db->query($q); return $q = $q->result_array();). Does this matter?
No, it should not be the problem. Could you put your code of how you've traslated the query by @DRapp using Code Igniter Active Record?
@m4t1t0 Suthan bala modified the answer a bit and now it is working,
1

Since we are counting, we need to make a minor change to DRap's Query:

select
      N.ID_News,
      N.Title,
      N.Body,
      N.Date_Created,
      N.Image,
      N.Category_ID,
      count(C.ID_Comments) CommentCount
   from
      News N
         LEFT JOIN Comments C
            on N.ID_News = C.News_ID
   order by
      whatever column(s) are important to you

That will only give you only one result.. as that query lacks a group by statement, I would recommend changing that query to this:

select
      N.ID_News,
      N.Title,
      N.Body,
      N.Date_Created,
      N.Image,
      N.Category_ID,
      count(C.ID_Comments) CommentCount
   from
      News N
         LEFT JOIN Comments C
            on N.ID_News = C.News_ID
   group by
      N.title
   order by
      whatever column(s) are important to you

Comments

0

Writing this down in the Active Record format stays something like this:

$this->db->select('N.ID_News, N.Title, N.Body, N.Date_Created, N.Image')
$this->db->select('N.Category_ID, count(C.ID_Comments) AS CommentCount');
$this->db->from('News AS N');
$this->db->join('commentas AS C', 'N.ID_News = C.News_ID', 'left');
$this->db->group_by('N.title');

After this you can use the order by funtion, to order the resultsas you seefit.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.