Codeigniter子查询

时间:2016-04-13 11:08:35

标签: php mysql codeigniter

我有这个问题可以帮助我将其转移到模型中的codeigniter样式。

SELECT
    a.*, 
    (
        SELECT COUNT(*) FROM `comment` c 
        WHERE c.comment_article_id = a.`News_News_ID`
    ) AS counta
FROM
    `news_news` a

更新: 我试试这个并且效果很好,但我不确定这是不错的做法

     $sql="SELECT a.*,
     ( SELECT COUNT(*) FROM comment c WHERE c.comment_article_id = a.`News_News_ID` ) as counta
     FROM `news_news` a";
 $query = $this->db->query($sql, array('News_Cate_ID' => $cate), $start, $display);

2 个答案:

答案 0 :(得分:0)

使用join代替sub query,根据您的查询,您在使用where

时不需要joins条件
$this->db->select('a.*,COUNT(c.*) AS counta');
$this->db->from('news_news AS a');
$this->db->join('comment AS c', 'c.comment_article_id = a.News_News_ID');
$query = $this->db->get();

了解更多information

答案 1 :(得分:0)

尝试以下代码。此查询将返回包含评论计数的每篇文章

$this->db->select('a.*,COUNT(c.*) AS count');
$this->db->from('news_news a');
$this->db->join('comment c', 'a.News_News_ID = c.comment_article_id ','LEFT');
$this->db->group_by('a.News_News_ID')
$query = $this->db->get();