2013-02-20 4 views
3

J'essaie de construire une requête MySql fonctionnelle avec une sous-requête corrélée dans zend_db_select (ZF 1.12) pour l'utiliser dans Zend_Paginator_Adapter. La requête de travail est la suivante:MYSql - Utilisation de la sous-requête corrélée dans Zend Db

SELECT f.*, (SELECT (COUNT(p.post_id) - 1) 
FROM `forum_topic_posts` AS p WHERE f.topic_id = p.topic_id) AS post_count 
FROM `forum_topics` AS f WHERE f.forum_id = '2293' 
ORDER BY post_count DESC, last_update DESC 

J'ai donc travaillé sur:

$subquery = $db->select() 
->from(array('p' => 'forum_topic_posts'), 'COUNT(*)') 
->where('p.topic_id = f.topic_id'); 

$this->sql = $db->select() 
->from(array('f' => 'forum_topics'), array('*', $subquery . ' as post_count')) 
->where('forum_id=?', $forumId, Zend_Db::PARAM_INT) 
->order('post_count ' . $orderDirection); 

Mais Zend arrête à l'exception suivante lors de l'exécution de la requête:

Zend_Db_Statement_Mysqli_Exception: Mysqli prepare error: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT COUNT(*) FROM forum_topic_posts AS p WHERE (p.topic_id = f.to' at line 1

Comment pourrais-je faire fonctionner la sous-requête?

Répondre

6

Voici la requête écrite à l'aide de l'interface Zend_Db OO.

La clé utilisait principalement des objets Zend_Db_Expr pour la sous-requête et COUNT pour la fonction.

$ss = $db->select() 
     ->from(array('p' => 'forum_topic_posts'), 
       new Zend_Db_Expr('COUNT(p.post_id) - 1')) 
     ->where('f.topic_id = p.topic_id'); 

$s = $db->select() 
     ->from(array('f' => 'forum_topics'), 
       array('f.*', 'post_count' => new Zend_Db_Expr('(' . $ss . ')'))) 
     ->where('f.forum_id = ?', 2293) 
     ->order('post_count DESC, last_update DESC'); 

echo $s; 
// SELECT `f`.*, SELECT COUNT(p.post_id) - 1 FROM `forum_topic_posts` AS `p` WHERE (f.topic_id = p.topic_id) AS `post_count` FROM `forum_topics` AS `f` WHERE (f.forum_id = 2293) ORDER BY `post_count DESC, last_update` DESC 
+0

Merci, cela fonctionne parfaitement. Je voudrais voter, mais je n'ai pas assez de réputation. – DerFlow