How can I pull latest posts, with unique authors, so that if an author wrote two posts in a row, it only gets the first?

StackOverflow https://stackoverflow.com/questions/23637585

문제

So right now, I have Posts and Authors... I want to make a "20 recent posts" section at my website.

Sometimes an author makes 4-5 posts in a row. In the 20 latest posts, I want all of these posts to have unique authors. So if author A wrote last 3 posts based on created_at, I only want the last post.

Hypothetically:

A wrote posts 10, 9, 7 B wrote posts 8, 6 C wrote posts 5, 1 D wrote posts 4, 3, 2

Then in the latest 4 posts section, I'd like posts: 10, 8, 7, 6

Or in any other manner where the author ID is unique, and I have 20 latest posts.

I've tried Post.select(:author_id).distinct, mapping, and other bits here and there, but I'm not sure if I'm going the right direction.

Thanks guys.

도움이 되었습니까?

해결책

This is the general idea. You can fill in the details.

 select author, maxts, etc
 from sometables join
 (select authorId, max(timestamp_field) maxts
 from etc
 where whatever
 group by authorId) temp on temp.authorId = author.authorId
 and sometable.timestamp_field = maxts
 where whatever

Make sure the "where whatever" is the same in both places.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top