开发者

LIMIT 1 for the top table WITH JOIN

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()
开发者_StackOverflow中文版->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.


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.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜