Mysql LEFT JOIN -> 获取最新主题id/主题标题

标签 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_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 

但现在我有点卡住了:(,它非常接近,但目前它仅在每个子论坛中列出第一个主题,我需要最后一个主题,但不知道如何。

最佳答案

查找最后一篇文章的子查询的问题在于,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 行,该行不存在具有更大的 last_post_time 的其他 forum_topics 行:

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 

关于Mysql LEFT JOIN -> 获取最新主题id/主题标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8174270/

相关文章:

php - 使用 laravel 从多个表进行多个查询

scala - FlinkML:加入 LabeledVector 的数据集不起作用

mysql - 不使用 UNION 重写 MySQL 查询

sql - 在不使用外部查询的情况下从每个组中获取第一个值的优雅方法

sql - 对于每个唯一的 A 列,什么 SQL 查询返回具有最新日期和时间(B 列和 C 列)的行?

php - 上传前预览 Excel 或 CSV 数据(可能是 AJAX?)

php - 搜索 php assoc array (hash map) 作为 mysql

MySQL:带有 JOIN 的 SUM() 返回不正确的值

用于将数量保存到 1 :M relationship 的 MySQL 表

php - 仅使用前 3 个值的数组的总和