用于计数的联接类型


Which type of join to use for counting?

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

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

我也将这种方法用于我的 Twitter 如分页,所以$last_pub_date就是这样做的。有了joinLeft()似乎很好,但当然,如果文章查询没有注释,则获取计数为 1 而不是 0。我尝试使用其他连接类型,但是如果没有注释,则不会获取整行$this->_db->order("pubDate DESC")或者无法正常工作。我也尝试使用子查询,但我不确定我是否按原样编写了它。

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

http://dev.mysql.com/doc/refman/5.1/en/group-by-functions.html#function_count