MYSql – 在Zend Db中使用相关子查询

我正在尝试使用zend_db_select(ZF 1.12)中的相关子查询构造一个有效的MySql查询,以便在Zend_Paginator_Adapter中使用它.工作查询如下:

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

所以我解决了:

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

但Zend在执行查询时会因以下异常而停止:

Zend_Db_Statement_Mysqli_Exception:Mysqli准备错误:您的SQL语法有错误;检查与MySQL服务器版本对应的手册,以便在’SELECT COUNT(*)FROM forum_topic_posts AS p WHERE(p.topic_id = f.to’,第1行)附近使用正确的语法

我怎么能让子查询工作?

最佳答案
这是使用Zend_Db OO接口编写的查询.

关键是主要使用一些Zend_Db_Expr对象作为子查询和COUNT函数.

$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

转载注明原文:MYSql – 在Zend Db中使用相关子查询 - 代码日志