0

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

选择 mt1.*, (select count(mt2.parent_id) from md_type as mt2 where mt2.parent_id = mt1.id)) as cnt from md_type as mt1

4

2 回答 2

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
于 2012-11-22T17:12:18.470 回答
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 - 子查询

于 2013-04-04T09:34:17.483 回答