2013-04-01 31 views
2

子查詢Zend框架2ZF2 - 子查詢

我需要查詢:

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` 

請幫助。

感謝, Anjith

+0

我們能看到你試過到目前爲止的代碼? – Rikesh

回答

15

我需要查詢:

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(); 

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

感謝您的回覆。

+0

+1此解決方案還允許後期變量綁定。甚至在將子查詢綁定到父查詢後修改子查詢。 – ArjanW

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') 
) 
+0

我正在使用Zend Framework 2,我可以在ZF2中使用它嗎? –

+0

是的,你可以..安傑斯 –

+0

謝謝,讓我檢查它 –

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" 
+0

建議的解決方案過早地序列化子查詢(實際上是兩次)。上面接受的解決方案延遲了子查詢的序列化,直到父查詢序列化 – ArjanW