SELECT t.id AS thread_id, t.headline AS thread_headline, t.posted_at AS thread_posted_at, r.posted_at AS last_reply_posted_at, r.id AS last_reply_id, (SELECT COUNT(*) FROM replies WHERE thread_id = t.id) AS num_replies FROM threads AS t JOIN replies AS r ON t.id = r.thread_id where not exists (select 1 from replies r1 where r1.thread_id = t.id and r1.posted_at < r.posted_at) ORDER BY thread_posted_at DESC, last_reply_posted_at DESC LIMIT 10