我正在尝试获取论坛中发布的最新主题,其中包含来自用户、主题和上一篇帖子的变量。问题是,我正在尝试的当前方法会带回重复的线程,因为较新的帖子已发布在这些线程中,而我只希望每个线程返回一个帖子,而不是所有最新的帖子。
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,只留下该线程中最新帖子条目的 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
最佳答案
这个查询的性能可能不是最好的,但如果不知道数据库的结构,我就无法做更多的事情。您还需要一些 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
关于php - MySql - 从表中获取最新行,没有重复的主题 ID,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22752685/