【问题标题】:Codeigniter 2.1 - join two tables and count in the same queryCodeigniter 2.1 - 连接两个表并在同一个查询中计数
【发布时间】:2012-12-03 16:23:37
【问题描述】:

我有两张桌子:

news ->     
  id_news    
  title    
  body    
  date_created    
  image    
  category_id    

comments ->     
  id_comments    
  news_id    
  body    
  date_created

如何编写查询以获取所有新闻、计算每个新闻的所有 cmets 并在视图部分显示该查询?

【问题讨论】:

  • 您能粘贴一下表格的结构吗?

标签: php mysql codeigniter codeigniter-2


【解决方案1】:
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

【讨论】:

  • 抱歉让您久等了。这是有效的,但我只得到一个消息,而不是全部。我猜这是因为此时只有一个新闻有 cmets 还是没关系?
  • 没关系,@DRapp 使用的是 LEFT JOIN
  • @m4t1t0 那么可能是什么问题呢? (在查询之后我有这部分 $q = $this->db->query($q); return $q = $q->result_array(); )。这有关系吗?
  • 不,应该不是问题。你能把你的代码说明你是如何使用 Code Igniter Active Record 通过@DRapp 翻译查询的吗?
  • @m4t1t0 Suthan bala 稍微修改了答案,现在它正在工作,
【解决方案2】:

由于我们正在计数,我们需要对 DRap 的 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

这只会给你一个结果。由于该查询缺少 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

【讨论】:

  • Suthan,对于未来,对于所提供答案的微小变化,通常只对那个人的答案发表评论以进行修复。我的反应很快,跳过了该组... @Sasha,但是,如果您说 5 个具有相同描述的标题,则此修订也可能失败。 group by 应该是新闻文章的“ID”。
  • 好的对不起,我试图在你的帖子下回复,但我没有看到添加评论按钮。谢谢。
  • @DRapp 建议已实施:)。
【解决方案3】:

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

在此之后,您可以使用 order by function,对结果进行排序。

【讨论】:

    猜你喜欢
    • 2010-10-24
    • 1970-01-01
    • 2011-05-02
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 2016-04-12
    • 2016-07-30
    • 1970-01-01
    相关资源
    最近更新 更多