我正试图加入一个所有主题所在的表格。我想要做的是列出所有论坛及其子类别,同时列出最新主题。
SELECT root.name AS root_name
, subcat.name AS subcat_name
, subcat.id AS subcat_id
, subcat.description AS subcat_description
, subcat.safe_url AS subcat_safe_url
, topics.*
FROM forum_category AS root
LEFT JOIN forum_category AS subcat ON subcat.parent_id = root.id
LEFT JOIN
(
SELECT MAX(`last_post_time`) AS aaaa, last_post_time, topic_title
, topic_id, forum_id
FROM `forum_topics`
WHERE 1
GROUP BY forum_id
) AS topics ON topics.forum_id = subcat.id
WHERE root.parent_id = 0
ORDER BY root_name, subcat_name
但是现在我有点卡住:(,它如此接近,但目前它只在每个子论坛列出第一个主题,我需要最后一个但不知道如何。
答案 0 :(得分:3)
您的子查询找到最后一篇文章的问题是,last_post_time,topic_title等没有理由属于具有MAX(last_post_time)的行。
考虑一下这个问题:
SELECT MAX(last_post_time), MIN(last_post_time), topic_title
FROM forum_topics
GROUP BY forum_id
返回哪个topic_title?那个帖子时间最长的那一行?那个帖子时间最少的那一行?这是不明确的 - MySQL只能从组中任意选择一个topic_title。在实践中,它从首先存储在组中的行中选择,并且在您的控制之外,取决于存储引擎实现等。
这是另一种设计,它找到了forum_topics行,其中没有其他forum_topics行存在且last_post_time更高:
SELECT root.name AS root_name
, subcat.name AS subcat_name
, subcat.id AS subcat_id
, subcat.description AS subcat_description
, subcat.safe_url AS subcat_safe_url
, topics.*
FROM forum_category AS root
LEFT JOIN forum_category AS subcat ON subcat.parent_id = root.id
LEFT JOIN forum_topics AS topics ON topics.forum_id = subcat.id
LEFT JOIN forum_topics AS t2 ON t2.forum_id = subcat.id
AND t2.last_post_time > topics.last_post_time
WHERE root.parent_id = 0 AND t2.forum_id IS NULL
ORDER BY root_name, subcat_name