我正在努力解决这个问题,即使Stack Overflow上有一些类似的问题,我找不到合适的解决方案。我有三个表:categories, topics
和posts
,我想加入它们,并在categories
中显示每个类别以及topics
发布了一些内容的最新主题在其中,最后是帖子从posts
表发布的最新日期。
我成功地将所有内容显示为我想要的,除了我无法从每个类别中获取最新的帖子记录。
以下是查询:
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
显然只会显示该类别的正确帖子,其中包含最新帖子。如何获取所有类别的最新帖子?
答案 0 :(得分: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行。
答案 1 :(得分:0)
首先:在您的Select查询中,您必须对GROUP BY子句中未包含的字段使用一些agregate函数。
现在。要获得每个类别的最大时间戳记的帖子,您必须进行两步查询。在第一步中,您将获得类别的最大时间戳,并在第二步中获得所有其他字段。是的,我们将使用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
这是一个解决方案, 更好的一个可能很好。