2012-10-31 57 views
0

我是Zf2的新蜂,所以請建議我應該如何在Zend框架2中創建以下sql?在zend框架中的子查詢計數2

選擇MT1 *, (SELECT COUNT(從md_type mt2.parent_id) 作爲MT2 其中mt2.parent_id = mt1.id))作爲CNT 從md_type爲MT1

回答

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 
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