我可以使用Zend_Db_Select重写这个吗?

And*_*ird 1 php mysql zend-framework

我需要编写以下查询:

SELECT forum_threads.id AS id_thread,
forum_threads.topic,
forum_threads.date_created,
forum_posts.content,
CONCAT(users.first, ' ', users.last) AS author_name 
  FROM forum_threads,forum_posts,users
     WHERE forum_threads.category_id=1
        AND forum_threads.author_id=users.id
        AND forum_posts.id=
            (SELECT id FROM forum_posts WHERE thread_id=`id_thread` ORDER BY date_posted ASC LIMIT 0,1)
Run Code Online (Sandbox Code Playgroud)

我不是要求任何人为我做这项工作.我只是在引用中找不到可以执行此类查询的任何内容.指出我正确的方向,这应该是我需要的一切.

我可以达到我需要子查询的地步,然后我不知道如何进步.有任何想法吗?

仅供参考:我想使用Zend_Db_Select对象,因为我将它发送到Zend_Paginator

澄清查询正在做什么:使用第一篇文章的内容拉长给定论坛类别的所有主题.

Bil*_*win 5

Zend_Db_Select在Zend工作期间开发了很多,同时我编写了文档和单元测试.

我通常的建议Zend_Db_Select你不必使用它.当您具有需要逐个构建查询的复杂应用程序逻辑时,它将被使用.如果您已经知道完整的SQL查询,那么将它作为字符串执行并且根本不使用它要容易得多Zend_Db_Select.

但为了回答您的问题,我在下面提供了一个解决方案.

我更改了查询,因此它不需要子查询.我使用了一招LEFT JOIN,以配合后p有没有其他早期的岗位p2具有相同thread_id.这应该比你拥有的子查询更有效.

$select = $db->select()
 ->from(array('t'=>'forum_threads'), array('id_thread'=>'id', 'topic', 'date_created'))
 ->join(array('p'=>'forum_posts'), 't.id=p.thread_id', array('content'))
 ->joinLeft(array('p2'=>'forum_posts'),
     't.id=p2.thread_id AND p.id > p2.id', array())
 ->join(array('u'=>'users'), 't.author_id = u.id',
     array('author_name'=>new Zend_Db_Expr("CONCAT(u.first, ' ', u.last)")))
 ->where('t.category_id = 1')
 ->where('p2.id IS NULL');
Run Code Online (Sandbox Code Playgroud)

我测试它,它有以下输出:

SELECT `t`.`id` AS `id_thread`, `t`.`topic`, `t`.`date_created`, `p`.`content`,
  CONCAT(u.first, ' ', u.last) AS `author_name` 
FROM `forum_threads` AS `t`
 INNER JOIN `forum_posts` AS `p` ON t.id=p.thread_id
 LEFT JOIN `forum_posts` AS `p2` ON t.id=p2.thread_id AND p.id > p2.id
 INNER JOIN `users` AS `u` ON t.author_id = u.id 
WHERE (t.category_id = 1) AND (p2.id IS NULL)
Run Code Online (Sandbox Code Playgroud)