php - 我可以使用 Zend_Db_Select 重写它吗?

标签 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)

我不会要求任何人为我完成工作。我只是在引用资料中找不到任何可以执行这样查询的内容。为我指明正确的方向,这应该是我所需要的一切。

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

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

澄清查询的作用:将给定论坛类别的所有线程与第一篇文章的内容拉在一起。

最佳答案

在为 Zend 工作期间,我开发了很多 Zend_Db_Select,还编写了文档和单元测试。

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

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

我更改了查询,因此它不需要子查询。我正在使用 LEFT JOIN 的技巧来匹配没有其他早期帖子 p2 的帖子 p 具有相同的 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');

我对此进行了测试,它具有以下输出:

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)

关于php - 我可以使用 Zend_Db_Select 重写它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1291906/

相关文章:

PHP 从字符串中删除除数字以外的所有内容

PHP 如何获取带有类和命名空间路径的方法名称作为字符串?

php - 要求输入密码短语/密码中的某些字符

php - Zend 中的 setScriptPath 找不到文件

forms - zend 表单依赖下拉列表

php - 使用 PHP 通过 SSL 从 Linux 为 iOS 应用程序推送通知

php - 用于检查空闲位置的 Symfony 实体查询构建器

mysql - 一次使用 LEFT JOIN 更新/创建多个

mysql - 在尝试使用 spring mvc Angular JS 保存数据时在数据库中存储空值

zend-framework - 使用 Zend Ldap 对 Windows AD 进行身份验证