2014-03-31 32 views
0

我正在嘗試獲取最新的帖子,這些帖子在用戶,主題和最後一篇帖子中都有vars。問題是我正在嘗試的當前方法帶回了重複線程,因爲新帖子已經發布在這些線程中,而我只想要一個帖子返回每個線程,而不是所有最新的帖子。MySql - 從表中獲取最新的行,沒有重複的主題ID

SELECT t.thread_id, u.user_name, p.post_entry 
FROM forum_thread as t 
LEFT JOIN forum_post AS p ON p.post_thread = t.thread_id 
LEFT JOIN user AS u ON u.user_id = p.post_user 
ORDER BY t.thread_lastpost DESC LIMIT 0,8 

目前正在返回:

/-----------------------------------------/ 
| 7049 | USERNAME | Post Entry | 
|----------------------------------------| 
| 7049 | USERNAME | Post Entry | 
|----------------------------------------| 
| 7049 | USERNAME | Post Entry | 
|----------------------------------------| 
| 7049 | USERNAME | Post Entry | 
|----------------------------------------| 
| 7650 | USERNAME | Post Entry | 
|----------------------------------------| 
| 7068 | USERNAME | Post Entry | 
|----------------------------------------| 
| 7056 | USERNAME | Post Entry | 
|----------------------------------------| 
| 7136 | USERNAME | Post Entry | 

我想刪除這些第一重複的ID,只留一個與該線程的最新帖子輸入。

我希望我已經解釋得足夠好讓人們理解。

謝謝。

-----------------編輯--------------------

得到它的工作與GROUP BY:

SELECT t.thread_id, u.user_id, p.post_entry 
FROM forum_post AS p 
LEFT JOIN forum_thread AS t ON t.thread_id = p.post_thread 
LEFT JOIN user AS u ON u.user_id = p.post_user 
GROUP BY t.thread_id 
ORDER BY t.thread_lastpost DESC LIMIT 0,8 
+1

不知道,但我認爲你可以解決這個使用GROUP BY的SQL語句,通過用戶名分組,通過插入ID排序,然後想起來了每個組中的第一個。對不起,但我無法做正確的查詢來幫助你。 –

+0

嘗試使用SELECT DISTINCT t.thread_id - DISTINCT關鍵字是此處的重要部分。 – Bryan

+0

我得到它與GROUP BY一起工作,但想知道什麼會更好的表現,或DISTINCT? –

回答

0

此查詢可能不是表現最好的,但不知道你的數據庫的結構,我不能做更多的事情。您還需要一些post_id或post_timestamp來包含第二個左連接。 DISTINCT和GROUP BY都不能解決您的問題,因爲用戶名和post_entry在所有情況下通常都會有所不同,即線條實際上並不是獨特的。

SELECT t.thread_id, u.user_name, p.post_entry 
FROM forum_thread as t 
LEFT JOIN forum_post AS p ON p.post_thread = t.thread_id 
LEFT JOIN forum_post AS p2 ON p.post_id > p2.post_id 
LEFT JOIN user AS u ON u.user_id = p.post_user 
where p2.post_id is null 
ORDER BY t.thread_lastpost DESC LIMIT 0,8 
+0

你發佈的原始工作,我發現之前你發佈。 thread_id和post_thread是完全相同的東西,只是在不同的表中,所以使用group by可以讓它返回我想要的結果。 –

相關問題