1

我正在建立一个基本论坛,我想获取创建的线程列表,但也most recent post从帖子表中获取,以便我可以显示last reply and time of last reply

我的尝试如何导致重复的结果,我尝试了 aLEFT JOIN和 aINNER 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

有谁知道我如何解决这个问题,所以它只会从与每个线程相关的帖子表中获取最后和最近的帖子,而不返回重复的线程?

4

1 回答 1

2

post_time下面的查询背后的想法是,它从post表中为threadid子查询中的每个找到最新的帖子 ( )。然后它重新加入原始表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
于 2012-10-16T00:46:37.960 回答