简体   繁体   English

LIMIT行,左连接

[英]LIMIT row with LEFT join

I have 'post' and 'comment' table. 我有“发布”和“评论”表。 I want select last 3 post and all comments for that posts. 我想选择最后3个帖子以及帖子的所有评论 Curently I use 2 separate statments: 我目前使用2个单独的陈述:

SELECT p.* FROM post p ORDER BY p.date DESC LIMIT 3; // called 1
SELECT c.* FROM comment c WHERE c.post_id = :id; // called 3x time for each post.

It's possible to marge this queries into one? 是否可以将这些查询合并为一个?

You can use a subquery for the set of posts: 您可以对一组帖子使用子查询:

SELECT p.*
FROM (SELECT p.*
      FROM post p
      ORDER BY p.date DESC
      LIMIT 3
     ) p JOIN
     comment c
     ON c.post_id = p.id
ORDER BY p.id, c.id;
SELECT   POST .*, COMMENT.* 
from POST INNER JOIN COMMENT ON POST.id = COMMENT.post_id
where  POST.id = COMMENT.post_id ORDER BY POST.id  LIMIT 3

You can also try this 您也可以尝试

SELECT p . * , c . * 
FROM post p
LEFT JOIN 
COMMENT c ON c.post_id = p.id
where p.id IN (SELECT id from post order by date desc limit 3) ORDER BY p.date

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM