我正在努力解决这个问题,即使 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
显然只会显示包含最新帖子的类别的正确帖子。如何获取所有类别的最新帖子?