[英]Intermediate mySQL Query - join two tables together and limit the results
Here is my table arrangement: 这是我的餐桌安排:
Posts
post_id
post_votes
Comments
comment_id
post_id
comment_time
I have failed to create a query that does the following: 我无法创建执行以下操作的查询:
I will post what I have tried if necessary. 如有必要,我会发布我尝试的内容。 I am just getting into more complicated queries, any help or suggestions is greatly appreciated
我正在进入更复杂的查询,非常感谢任何帮助或建议
The below will retrieve 10 post order by desc and also 5 comments order by desc respectively. 下面将通过desc检索10个发布订单,并分别通过desc检索5个评论。
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 (testing sample of retrieving 3 post order by desc and also 2 comments for each post respectively). SQL FIDDLE HERE (测试通过desc检索3个帖子的样本,并分别为每个帖子检索2个评论)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.