LIMIT 1 对于顶级表WITH JOIN
我使用 PHP、MySQL 和 Zend Framework。我有一些具有简单关系的简单表格。
post_category - post (1:1)
post - post_comments (1:M)
我需要使用 1 个查询选择带有评论的最后一篇文章。这是我获取所有帖子的查询:
$select = $this->select()
->setIntegrityCheck(false)
->from(array('p' => 'post'))
->join(array('pc' => 'post_category'), 'pc.id = p.category_id',
array('category_name' => 'name', 'category_name_key' => 'name_key'))
->joinLeft('post_comment', 'p.id = post_comment.post_id',
array('comment_id' => 'id', 'created_by', 'comment', 'comment_date_creation' => 'date_creation'))
->order('p.date_creation desc');
我无法添加 ->limit(1)
因为查询可以返回多行。我怎样才能避免这种情况呢?我不想创建 2 个查询。
提前谢谢您。
I use PHP, MySQL and Zend Framework. I have some simple tables with simple relations.
post_category - post (1:1)
post - post_comments (1:M)
I need to select last post with comments using 1 query. It is my query for getting all posts:
$select = $this->select()
->setIntegrityCheck(false)
->from(array('p' => 'post'))
->join(array('pc' => 'post_category'), 'pc.id = p.category_id',
array('category_name' => 'name', 'category_name_key' => 'name_key'))
->joinLeft('post_comment', 'p.id = post_comment.post_id',
array('comment_id' => 'id', 'created_by', 'comment', 'comment_date_creation' => 'date_creation'))
->order('p.date_creation desc');
I can not add ->limit(1)
cause query can returns more than one row. How can I avoid this situation? I not want to create 2 queries.
Thank you in advance.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我可能读错了,但如果我理解正确,你想要获取该帖子及其评论,但将其限制为最新的帖子...
如果是这种情况,为什么不先添加 WHERE 子句和子查询.. .p.id = (SELECT Max(id) from post)
理论上,这应该将其过滤到最新输入的帖子。另一个选项是选择最大日期时间(如果有这样的字段)。
I may be reading this wrong, but if I am understanding you correctly you want to get the post and its comments but limit it to the most recent post...
if thats the case why not add a WHERE clause and a subquery first...p.id = (SELECT Max(id) from post)
In theory this should filter it to the latest post entered. The other option is to select on the max datetime if there is such a field.