2012-10-16 40 views
1

我建立一個基本的論壇,我想抓住創建的線程的列表中,但也抓住從職位表中的most recent post,所以我可以顯示last reply and time of last reply從另一個表

如何過選擇最近我行嘗試導致重複的結果,我嘗試了一個LEFT JOIN和一個INNER JOIN具有相同的結果。我希望有人知道解決方案。

這是我的嘗試:

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 

任何一個人知道我可以解決這個問題,所以它只會得到有關每個線程後表中最後一個和最近的職位,而無需返回重複的主題?

回答

2

下面的查詢背後的想法是,它發現從post表中的每個threadid子查詢中最近的職位(post_time)。然後它回到原表postthreads表上。

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 
+0

非常感謝! – Sir

+0

歡迎戴夫! –