2011-07-17 31 views
1

所以,我寫一個小論壇,我想列出以下獲取線程+用戶名最後的海報

  • 線程話題
  • 的誰啓動線程的用戶名
  • 的當它開始
  • 誰在線程寫帖子的最後的
  • 日期的最後一個人的用戶名日期

我有三個表此

帳戶

+---------------+ 
| id | username | 
|---------------+ 
| 1 | blargh | 
| 2 | hest  | 
+---------------+ 

線程

+----+-------+------+---------+ 
| id | topic | user | thedate | 
+----+-------+------+---------+ 
| 5 | Yarr | 1 | bleh | 
+-------------------+---------+ 

帖子

+----+---------+------+---------+--------+ 
| id | content | user | thedate | thread | 
+----+---------+------+---------+--------+ 
| 8 | aaaa | 1 | aadate | 5  | 
+----+---------+------+---------+--------+ 
| 9 | bbbb | 2 | bbdate | 5  | 
+----+---------+------+---------+--------+ 

我想要什麼:

+----+-------+----------+---------+--------------------+----------------+ 
| id | topic | username | thedate | last_post_username | last_post_date | 
+----+-------+----------+---------+--------------------+----------------+ 
| 5 | Yarr | blarg | bleh | hest    | bbdate   | 
+----+-------+----------+---------+--------------------+----------------+ 

這是我走到這一步:

SELECT 
forum_threads.id AS id, 
forum_threads.topic AS topic, 
forum_threads.time AS time, 
accounts.username AS username, 
Max(forum_posts.id) AS latest_post_id, 
forum_posts.`user` AS `user`, 
forum_posts.timeposted AS last_post_time 
FROM 
((forum_threads 
JOIN forum_posts ON ((forum_posts.thread = forum_threads.id))) 
JOIN accounts ON ((forum_threads.`user` = accounts.id))) 

我似乎無法獲得最後的海報的用戶名和時間後說

+2

爲什麼不直接使用已經在網絡上使用多年的成熟論壇軟件? –

+2

爲了它的樂趣。 – Softnux

+0

您的表格和「您想要的」與您的查詢不匹配得很好,這使得爲您寫出一個好答案變得更加困難,但可能最簡單的方法就是添加一個where條件要求'forum_posts.timeposted'等於從forum_posts返回max'timeposted'的子查詢,其中'thread = forum_threads.id'。 – jswolf19

回答

0

首先 - 我看不到任何東西在你的將帖子鏈接到線索的架構。我的答案是假設posts中有一個名爲threadid的附加列。

我發現這個問題最常見的解決方案是跟蹤threads表中最新帖子的ID(可能還有用戶ID和用戶名)。這很容易獲得的最新訊息,如果你需要的是在ID:

SELECT threadid, MAX(id) FROM posts WHERE <...> GROUP BY threadid 

但目前還沒有有效的方式來獲得該查詢相關的時間或用戶ID。我能得到的最接近的是這個爛攤子:

SELECT threadid, id, user, username, thedate FROM posts 
WHERE posts.id IN (
    SELECT threadid, MAX(id) FROM posts WHERE <...> GROUP BY threadid 
) 

這是令人難以置信的低效率在MySQL - 優化完全分崩離析上有GROUP BY子查詢。 (在一個測試數據庫下,查詢需要大約300毫秒的時間,但是在一百個線程之下)。只需咬緊舌頭,通過在線程中存儲最新帖子的信息來反規範化數據庫,並且一切都會好的。

+0

嗯,是的,你是對的,帖子表中應該有一個線程列。 – Softnux