在zend框架2中的子查询中计数

时间:2012-10-31 10:11:50

标签: zend-framework2

我是Zf2的新蜜蜂,所以请建议我如何在Zend框架2中创建以下sql?

选择mt1。*, (选择计数(mt2.parent_id)  从md_type作为mt2  其中mt2.parent_id = mt1.id))作为cnt 从md_type作为mt1

2 个答案:

答案 0 :(得分:1)

你可以试试这个:

$sub = new Select('md_type');
$sub->columns(array(new Expression('COUNT(mt2.parent_id) as total')))
    ->where(array(
        new \Zend\Db\Sql\Predicate\Expression('mt2.parent_id = mt1.id')
    ))
;

$subquery = new \Zend\Db\Sql\Expression("({$sub->getSqlString()})");

$select = new \Zend\Db\Sql\Select('mt1');
$select->columns(array('*', 'cnt' => $subquery));

这会产生:

SELECT mt1.*, 
    (SELECT COUNT(mt2.parent_id) as total 
     FROM "md_type" 
     WHERE mt2.parent_id = mt1.id
    ) AS cnt 
FROM mt1

答案 1 :(得分:0)

请试试这个

$sql = new Sql($this->_adapter);
$mainSelect = $sql->select()->from('mt1');
$subQry = $sql->select()
        ->from('md_type')
        ->columns(array('orderCount' => new \Zend\Db\Sql\Expression('COUNT(md_type.parent_id)')))
        ->where('mt2.parent_id = mt1.id');
$mainSelect->columns(
        array(
            'id', 
            'total' => new \Zend\Db\Sql\Expression('?', array($subQry)),
        )
);

$statement = $sql->prepareStatementForSqlObject($mainSelect);
$comments = $statement->execute();
$resultSet = new ResultSet();
$resultSet->initialize($comments);

return $resultSet->toArray();

参考:ZF2 - subqueries