Codeigniter 2.1 - 连接两个表并计入同一查询

时间:2012-12-03 16:23:37

标签: php mysql codeigniter codeigniter-2

我有两张桌子:

news ->     
  id_news    
  title    
  body    
  date_created    
  image    
  category_id    

comments ->     
  id_comments    
  news_id    
  body    
  date_created

如何编写查询以获取所有新闻,计算每条新闻的所有评论并在视图部分中显示该查询?

3 个答案:

答案 0 :(得分: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

答案 1 :(得分:1)

由于我们在计算,我们需要对DRap的查询做一个小改动:

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

这只会给你一个结果..因为该查询缺少group by语句,我建议将该查询更改为:

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

答案 2 :(得分:0)

以Active Record格式写下来的内容类似于:

$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');

在此之后,您可以按功能使用订单,来订购您认为合适的结果。