SQL-如何提取不重复的论坛主题?

时间:2010-02-06 17:58:51

标签: php sql forum punbb

在我网站的主页上,我想向论坛显示最新帖子,但我不想两次显示相同的主题。如何修改下面的代码来执行此操作?

http://punbb.informer.com/wiki/punbb13/integration#recent_10_posts

基本上显示最新帖子,但每个论坛主题/帖子只显示一次。

3 个答案:

答案 0 :(得分:3)

添加条件以仅保留帖子是主题中最后一篇帖子的记录:

WHERE p.id = (
  SELECT pp.id 
  FROM posts AS pp
  WHERE pp.topic_id = t.id ORDER BY pp.posted DESC LIMIT 1
)

答案 1 :(得分:1)

更改此行

'SELECT'    => 'p.id, p.message, t.subject',

'SELECT DISTINCT'   => 'p.id, p.message, t.subject',

答案 2 :(得分:1)

如果每个主题只需要一个值,则可以按主题分组,并从每个主题中选择最新的帖子。然后,您可以选择前10个主题。

我将用SQL编写它,你可以将其翻译成PHP:

SELECT p.id, p.message, o.subject
FROM
((SELECT t.id
  FROM posts AS p LEFT JOIN topics AS t ON p.topic_id = t.id
  GROUP BY t.id
  HAVING p.posted = MAX(p.posted) ) ids LEFT JOIN topics AS t ON ids.id = t.id) o
                                        LEFT JOIN posts AS p ON o.id = posts.topic_id
ORDER BY p.posted DESC
LIMIT '0,10'