【问题标题】:MYSql - Using correlated subquery in Zend DbMYSql - 在 Zend Db 中使用相关子查询
【发布时间】:2013-02-20 23:57:38
【问题描述】:

我正在尝试使用 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 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

我怎样才能让子查询工作?

【问题讨论】:

    标签: mysql zend-framework zend-db correlated-subquery


    【解决方案1】:

    这是使用Zend_Db OO 接口编写的查询。

    关键在于子查询和COUNT函数主要使用了一些Zend_Db_Expr对象。

    $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
    

    【讨论】:

    • 谢谢,完美。想投票但没有足够的声誉。
    猜你喜欢
    • 2010-11-23
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-24
    • 1970-01-01
    • 2020-09-27
    • 2011-06-09
    • 2019-09-15
    相关资源
    最近更新 更多