Mysql左连接->;获取最新的主题id/主题标题

Mysql左连接->;获取最新的主题id/主题标题,mysql,join,greatest-n-per-group,Mysql,Join,Greatest N Per Group,我试图左键联接所有主题所在的表。我想做的是列出所有论坛及其子类别,同时列出最新主题 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_categor

我试图左键联接所有主题所在的表。我想做的是列出所有论坛及其子类别,同时列出最新主题

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 

但是现在我有点被卡住了:(,虽然很近,但目前它只在每个子论坛中列出了第一个主题,我需要最后一个主题,但不知道如何使用。

查找最后一篇文章的子查询的问题是,没有理由将最后一篇文章的时间、主题标题等归入具有MAX(最后一篇文章的时间)的行

考虑一下这个问题:

SELECT MAX(last_post_time), MIN(last_post_time), topic_title
FROM forum_topics
GROUP BY forum_id
返回哪个主题标题?发布时间最多的一行?发布时间最少的一行?这是不明确的——MySQL只能从组中任意选择一个主题标题。实际上,它从组中第一个物理存储的行中进行选择,这超出了您的控制范围,具体取决于关于存储引擎的实现等

这里有一种替代设计,用于查找论坛主题行,该行没有其他论坛主题行具有更大的最后发布时间:

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 

哎呀,逗号的开头伤了我的眼睛。我从来没有真正想过,我觉得它看起来不错:)嘿,比尔,谢谢你给我一个很好的回答!我想我现在终于明白了。。。我和这个人吵了一整天。我从来没有想过像你那样做,但这是有道理的。