选择每个子查询的前n行

时间:2014-01-27 20:19:16

标签: mysql sql

我有这个结构:

posts:
    id, content, created_at

comments:
    id, post_id, content, created_at

现在我想选择由created_at desc订购的10个帖子, 限制只有10个帖子。 现在问题, 我想让每篇帖子最后5条评论。

我分开做这个没有问题,但它会产生11个查询...... 一个人获得帖子, 每个帖子另外10个查询并选择它的评论。

有关如何减少此查询的任何想法?

2 个答案:

答案 0 :(得分:3)

这是一种方式:

select c.*
from (select p.*
      from posts p
      order by createdat desc
      limit 10
     ) p10 left outer oin
     comments c
where 5 >= (select count(*)
            from comments c2
            where c2.post_id = c.post_id and c2.created_at >= c.created_at
           );

这适用于索引posts(createdat)comments(post_id, created_at)

答案 1 :(得分:1)

SELECT   p.id,p.content,p.created_at 
FROM posts p 
ORDER BY created_at DESC LIMIT 10
JOIN 
(SELECT id, post_id, content, created_at 
FROM comments 
ORDER BY created_at DESC 
LIMIT 5)x
ON x.post_id=p.id