2

Zend Framework 2 中的子查询

我需要的查询:

SELECT `comment`.`id` AS `commentId`, `comment`.`comment` AS `comment`, 
        (SELECT COUNT(`comment_vote`.`id`) AS `negativeVote` 
        FROM `comment_vote` 
        WHERE vote = -1 
        AND `comment_vote`.`commentId` = `comment`.`id`) AS `nagetiveVoteCount` 
FROM `comment`

请帮忙。

谢谢,安吉斯

4

3 回答 3

16

我需要的查询:

SELECT `comment`.`id` AS `commentId`, `comment`.`comment` AS `comment`, 
            (SELECT COUNT(comment_vote.id) AS `negativeVote` 
            FROM `comment_vote` 
            WHERE vote = -1 
            AND comment_vote.commentId = comment.id) AS `nagetiveVoteCount` 
            FROM `comment`

我如何使用 Zend Framework 2 创建:

$sql = new Sql($this->_adapter);
$mainSelect = $sql->select()->from('comment');
$selectPost = $sql->select()
        ->from('comment_vote')
        ->columns(array('negativeVote' => new \Zend\Db\Sql\Expression('COUNT(comment_vote.id)')))
        ->where('vote = -1')
        ->where('comment_vote.commentId = comment.id');
$mainSelect->columns(
        array(
            'commentId' => 'id', 'comment',
            'nagetiveVoteCount' => new \Zend\Db\Sql\Expression('?', array($selectPost)),
        )
);

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

return $resultSet->toArray();

参考:http : //eltonminetto.net/blog/2013/03/21/subqueries-no-zend-framework-2/

感谢所有的回复。

于 2013-04-01T12:12:14.497 回答
3
Solution for the above query in ZF2:

$sub = new Select('comment_vote');
$sub->columns(array('negativeVote' => new \Zend\Db\Sql\Expression('COUNT(comment_vote.id)')), FALSE)->where(array('vote' => -1 , 'comment_vote.commentId' => 'comment.id'));
$subquery = new \Zend\Db\Sql\Expression("({$sub->getSqlString()})");
$predicate = new \Zend\Db\Sql\Predicate\Expression("({$sub->getSqlString()})");


$sql = new Sql($this->adapter);
$select = $sql->select()->from('comment');
$select->columns(array('commentId','comment', 'nagetiveVoteCount' => $subquery));
echo $select->getSqlString();

它将返回输出:

SELECT "comment"."commentId" AS "commentId", 
       "comment"."comment" AS "comment", 
       (SELECT COUNT(comment_vote.id) AS "negativeVote" 
          FROM "comment_vote" 
           WHERE "vote" = '-1' 
           AND "comment_vote"."commentId" = 'comment.id') AS "nagetiveVoteCount" 
 FROM "comment"
于 2014-01-09T10:28:01.380 回答
0
$db->select()
->from ('table1', array('t1_label'))
->joinInner(
      array('T2' => new Zend_Db_Expr (
         '('.
         $db->select()
         ->from('table2', array('t2_label'))
         ->where('condition')
         .')'
      )),
      'table1.t2_id = T2.t2_id',
      array('t2_label')
)
于 2013-04-01T11:17:06.080 回答