Php 要使用哪种类型的联接进行计数?

Php 要使用哪种类型的联接进行计数?,php,mysql,zend-framework,zend-db,zend-db-table,Php,Mysql,Zend Framework,Zend Db,Zend Db Table,我尝试了不同的连接类型,但无法确定应该使用哪种类型。我想计算每篇文章的评论数 $select = $this->_db->select() ->from($this->_name) ->joinLeft('categories', 'categories.cat_id = ' . $this->_name . '.category', array('category_name' => 'name')) -&

我尝试了不同的连接类型,但无法确定应该使用哪种类型。我想计算每篇文章的评论数

$select = $this->_db->select()
        ->from($this->_name)
        ->joinLeft('categories', 'categories.cat_id = ' . $this->_name . '.category', array('category_name' => 'name'))
        ->joinLeft('comments', 'comments.post_id = ' . $this->_name. '.post_id', array('num_comments' => 'COUNT(*)'))
        ->group($this->_name.'.post_id')
        ->limit(3)
        ->order("pubDate DESC");
if($category_id > 0) $select->where("category = ?", $category_id);
if($last_pub_date > 0) $select->where("$this->_name.pubDate < ?", $last_pub_date);
$select=$this->\u db->select()
->从($this->\u name)
->joinLeft('categories','categories.cat_id='。$this->_name.'.category',数组('category_name'=>'name'))
->joinLeft('comments','comments.post_id='。$this->_name.'.post_id',array('num_comments'=>'COUNT(*))
->组($this->\u name.'.post\u id'))
->限制(3)
->订单(“发布日期描述”);
如果($category\u id>0)$select->where(“category=?”,$category\u id);
如果($last\u pub\u date>0)$select->where($this->\u name.pubDate<?“,$last\u pub\u date);

我也将此方法用于类似于Twitter的分页,因此,
$last\u pub\u date
适用于此。使用
joinLeft()
似乎不错,但如果没有对文章查询的注释,则获取的计数将为1而不是0。我尝试使用其他连接类型,但如果没有注释,则不会获取整行,或者
$this->\u db->order(“pubDate DESC”)
无法正常工作。我也尝试过使用子查询,但我不确定我是否编写了它

左连接是右连接,但是您需要使用
COUNT(comment\u id)
而不是
COUNT(*)
COUNT(*)
将返回行数,即使没有注释,行数也将为一
COUNT(comment\u id)
将返回非
NULL
comment\u id
值的数量,这应该是您要查找的