I try to work with the following tables: users (id, name) threads (id, name, slug) messages (id, title, content, topicid, authorid, datetime, slug) responses (id, authorid, threadid, content, datetime)
I want to create a list of posts sorted by most recent reply (or publication date if there are no replies). Each list should contain: title of the post, number of answers, date of publication, date of the last answer, name of the author, name of the person who last answered, etc.
I can get everything except the date and the author of the last answer. Date can be done via MAX (replies.datetime), but I'm not sure how to get the last author.
My last attempt was to use an exception:
select posts.id, posts.title, posts.authorid, posts.topicid, posts.content, posts.datetime, count(replies.id) as replies, r2.datetime, replies.datetime, GREATEST(posts.datetime, coalesce(max(replies.datetime), posts.datetime)) as latesttime, users.name as author, commenters.name as commenter, r2.id from posts left join replies on replies.threadid = posts.id left join users on users.id = posts.authorid left join users commenters on commenters.id = replies.authorid left join replies as r2 on replies.id = r2.id and replies.datetime < r2.datetime where r2.id is null group by posts.id order by latesttime DESC, replies.datetime DESC limit 20;
Unfortunately, this will not get the last commenter anyway. Any ideas?