Zend Framework 2:sql子查询

时间:2012-10-28 15:42:51

标签: php zend-framework2

在ZF1中它的工作原理如下:

 $selectColumns = array(
   '*',
   'orders_total' => "(".$db->select()->from("orders", array("COUNT(*)"))->where("orders.parent_id=mytable.id").")",
 );
 $select = $db->select()->from('mytable', $selectColumns);

如何在ZF2中执行此操作?感谢。

4 个答案:

答案 0 :(得分:7)

请试一试。

$sql = new Sql($this->_adapter);
$mainSelect = $sql->select()->from('mytable');
$subQry = $sql->select()
        ->from('orders')
        ->columns(array('orderCount' => new \Zend\Db\Sql\Expression('COUNT(orders.id)')));
$mainSelect->columns(
        array(
            'id', 
            'orders_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

答案 1 :(得分:1)

你可以试试这个:

// Make your query here using the builder if you wish, 
// but we will need to convert to string for the Expression
$sub = new Select('orders');
$sub->columns(array(new Expression('COUNT(*) as total')))
    ->where(array('id' => 4))
;
// You could just create an expression..
$subquery = new \Zend\Db\Sql\Expression("({$sub->getSqlString()})");

$select = new \Zend\Db\Sql\select('tablename'); // this is inside a 

$select->columns(array('*', 'orders_total' => $subquery));

输出将是这样的:

SELECT 
    .*, 
    (SELECT COUNT(*) as total FROM "orders" WHERE "id" = '4') AS orders_total 
FROM tablename

我还没有找到一种很好的方法来使用查询构建器来执行这些类型的查询,而无需使用原始查询。

答案 2 :(得分:0)

如果没有更多信息,您可以尝试:

 $selectColumns = array(
    '*',
    'orders_total' => "(".$db->select()->from("orders", array("COUNT(*)"))->where("orders.parent_id", "mytable.id").")",
);
 $select = $db->select()->from('mytable', $selectColumns);

您需要在顶部添加use语句:

use Zend\Db\Sql\Select;
use Zend\Db\Sql\Where;

答案 3 :(得分:0)

您可以尝试将SQL重构为:

SELECT
    *,
    SUM(IF(O.parent_id IS NULL, 0, 1)) AS orders_total
FROM mytable
    LEFT JOIN orders O ON mytable.id = O.parent_id

您可以使用Zend Framework 2代表:

$select = new Select('mytable');
$select->columns(array(
    '*',
    'orders_total' => new Expression("SUM(IF(O.parent_id IS NULL, 0, 1))")
));
$select->join(array('O', 'orders'), 
              "mytable.id = O.parent_id",
              Select::JOIN_LEFT);   
$select->group(array('mytable.id'));

$result = $dbh->selectWith($select);

假设$ dbh是您的数据库适配器。