0

这是我的餐桌布置:

Posts
   post_id
   post_votes

Comments
   comment_id
   post_id
   comment_time

我未能创建执行以下操作的查询:

  1. 按 post_votes desc选择 10 个帖子排序
  2. 每篇文章获得 5 条评论

如有必要,我将发布我尝试过的内容。我刚刚进入更复杂的查询,非常感谢任何帮助或建议

4

1 回答 1

2

下面将分别检索 10 个按 desc 的帖子顺序和 5 个按 desc 的评论顺序。

select post_id,post_votes,comment_id,comment_time,
 @rn := CASE WHEN @prev_post_id = post_id THEN @rn + 1 ELSE 1 END AS rn,
        @prev_post_id := post_id from
  (select p.post_id,post_votes,comment_id,comment_time from
  (SELECT post_id,post_votes from posts order by post_votes desc limit 10) p 
   left outer join 
   comments c on p.post_id=c.post_id order by post_id,comment_time desc )m
having rn<=5

SQL FIDDLE HERE(通过 desc 检索 3 个 post order 的测试示例,以及每个 post 的 2 个评论)。

于 2012-09-13T03:37:16.833 回答