如何在Zend_Db_Select中创建COUNT AS?

时间:2013-08-21 15:20:48

标签: php mysql zend-framework zend-db

所以我有这个问题:

select u.*, count(mi.media_id) as media_count
from user as u
left join media_items as mi on mi.user_id = u.user_id
where u.is_enabled = 1 and
group by u.user_type
having media_count > 0;

我正在尝试将其翻译为Zend_Db_Select。到目前为止,除了媒体的数量,我还有其他一切。这就是我试过的:

$select->from(array('u' => 'user'), array('*', new Zend_Db_Expr('COUNT(mi.media_id) AS media_count'))
       ->joinLeft('mi' => 'media_items'), 'mi.user_id = u.user_id')
       ->where('u.is_enabled = 1')
       ->group('u.user_type')
       ->having('media_count > 0');

这让我错误:

"Mysqli prepare error: Unknown column 'media_count' in 'having clause'"

如何以Zend方式创建此语句?

另外,我输出了这个创建的查询并在MySQLWorkBench上运行它运行得很好。

编辑 我刚刚尝试过:

->columns('media_count' => new Zend_Db_Expr('COUNT(mi.media_id)'))

同样的错误。

1 个答案:

答案 0 :(得分:1)

这应该可以正常运作:

$select->from(array('u' => 'user'), array('*', 'media_count' => 'count(mi.media_id)'))
   ->joinLeft('mi' => 'media_items'), 'mi.user_id = u.user_id')
   ->where('u.is_enabled = 1')
   ->group('u.user_type')
   ->having('media_count > 0');