I have the above models in my MySQL database:
Blogs (id: integer, name: varchar)
Posts (id: integer, name: varchar, blog_id: integer, created_at: date)
I want to retrieve a list of all the blogs, ordered by the ones that have the newests posts.
I’ve reached that with the following query:
SELECT b.*, (SELECT p.created_at FROM posts p WHERE p.blog_id = b.id ORDER BY p.created_at DESC LIMIT 1) AS last_post_created_at FROM blogs b ORDER BY last_post_created_at DESC;
But this query is too slow and I’m unable to use it on my application.
Do you guys have a good solution for that?
Thank you.
A rewriting of the query:
An index on
(blog_id, created_at)will help both this and your version.If you want to limit the number of blogs returned, you should add the
ORDER BYin the subquery and put theLIMITthere: