Reputation: 8277
I'm building a basic forum, and i want to grab the list of threads created but also grab the most recent post
from the post table so i can display last reply and time of last reply
How ever my attempt is causing duplicate results, i tried a LEFT JOIN
and a INNER JOIN
with the same outcome. I was hoping someone knew the solution.
This is my attempt:
SELECT t1.username as thread_starter,
t2.username as last_reply_username,
t1.thread_time as thread_start,
t2.post_time as last_reply_time,
t1.title,
t1.sticky
FROM threads t1
INNER JOIN posts t2
ON t1.id = t2.threadid
ORDER BY t1.sticky DESC, t2.post_time DESC
Does any one know how i can solve the problem so it will only get the last and most recent post from the post table related to each thread without returning duplicate threads?
Upvotes: 1
Views: 81
Reputation: 263893
The idea behind the query below is that it finds the most recent post (post_time
) from the post
table for each threadid
inside the subquery. Then it joins back on the original table post
and threads
table.
SELECT a.username AS Thread_Starter,
c.username AS Last_reply_username,
a.thread_time AS Thread_Start,
c.post_time AS Last_Reply_Time,
a.Title,
a.Sticky
FROM threads a
INNER JOIN
(
SELECT threadID, MAX(Post_Time) lastPost
FROM post
GROUP BY ThreadID
) b ON a.threadID = b.threadID
INNER JOIN post c
ON b.threadID = c.ThreadID AND
b.lastPost = c.post_time
ORDER BY a.sticky DESC, c.post_time DESC
Upvotes: 2