1

我正在努力解决这个问题,即使 Stack Overflow 上有一些类似的问题,我也找不到正确的解决方案。我有三个表格:我想在哪里加入它们并显示每个类别categories, topics以及其中发布的最新主题的主题,最后是表格中发布该帖子的最新日期。postscategoriestopicsposts

除了我无法从每个类别中获取最新的帖子记录外,我成功地让所有内容都按我想要的方式显示。

这是查询:

SELECT c.cat_id, c.cat_name, c.cat_description, t.topic_subject, t.topic_id, p.post_date FROM categories c 
LEFT JOIN topics t ON c.cat_id = t.topic_cat 
LEFT JOIN posts p ON p.post_topic = t.topic_id AND p.post_date = ( SELECT MAX(post_date) as post_date FROM posts WHERE post_topic = t.topic_id ) 
GROUP BY c.cat_id ORDER BY UNIX_TIMESTAMP(post_date) DESC

我意识到这应该与topic_id子句WHERE中的不是我正在寻找的那个有关。另一个这样的:

SELECT c.cat_id, c.cat_name, c.cat_description, t.topic_subject, t.topic_id, p.post_date FROM categories c 
LEFT JOIN topics t ON c.cat_id = t.topic_cat AND t.topic_id = ( SELECT post_topic FROM posts ORDER BY UNIX_TIMESTAMP(post_date) DESC LIMIT 1 ) 
LEFT JOIN posts p ON p.post_topic = t.topic_id AND p.post_date = ( SELECT MAX(post_date) as post_date FROM posts WHERE post_topic = t.topic_id ) 
GROUP BY c.cat_id ORDER BY UNIX_TIMESTAMP(post_date) DESC

显然只会显示包含最新帖子的类别的正确帖子。如何获取所有类别的最新帖子?

4

2 回答 2

1
SELECT c.cat_id, c.cat_name, c.cat_description, tp.topic_subject, tp.topic_id, tp.maxPostDate
FROM categories c 

LEFT JOIN (select t.topic_cat,t.topic_subject,t.topic_id, max(post_date) maxPostDate  from topics t
           LEFT JOIN posts p ON p.post_topic = t.topic_id
           group by t.topic_cat,t.topic_subject,t.topic_id) tp
on (c.cat_id=tp.topic_cat)


where tp.maxPostDate = (select max(post_date) from topics t2
                       LEFT JOIN posts p2 ON p2.post_topic = t2.topic_id
                       where t2.topic_cat=c.cat_id
                       )


ORDER BY UNIX_TIMESTAMP(tp.maxPostDate) DESC

注意:如果该查询有 2 个不同主题且最大发布日期相同,则该查询可以为一个类别输出例如 2 行。

于 2012-08-10T12:35:37.623 回答
0

首先:在您的 Select 查询中,您必须对未包含在 GROUP BY 子句中的字段使用一些聚合函数。

现在。要获得每个类别的最大时间戳的帖子,您必须进行两步查询。在第一步中,您将获得类别的最大时间戳,然后是所有其他字段。是的,我们将使用 cat_id + timestamp 作为主键。它可以为相同的 cat_id 提供一些重复的记录,但在实时情况下会非常奇怪。

代码将类似于:

SELECT c.cat_id, MAX( p.post_date ) as max_date
into #tmp_table
FROM categories c 
    LEFT JOIN topics t ON c.cat_id = t.topic_cat 
    LEFT JOIN posts p ON p.post_topic = t.topic_id 
GROUP BY c.cat_id 

SELECT * -- what you'll need
from #tmp_table as tmp
    LEFT JOIN categories as c on c.cat_id = tmp.cad_id
    LEFT JOIN topics t ON c.cat_id = t.topic_cat 
    LEFT JOIN posts p ON p.post_topic = t.topic_id AND p.post_date = tmp.max_date
-- order by -- what you'll need

这是一个解决方案,更好的解决方案可能会很好。

于 2012-08-10T12:16:20.113 回答