按另一个表列排序(如果存在)


Ordering By Another Table Column If Exists

我正在整理一个简单的论坛脚本和主题/帖子。我正在尝试按最新帖子对主题进行排序,并且我很幸运地得到了以下问题的答案:MYSQL 从另一个表中订购,但我遇到的问题是某些主题还没有任何帖子,因此查询根本不选择这些主题。

当前的编码是:

SELECT DISTINCT forum.* 
FROM forum 
INNER JOIN forum_posts 
      ON forum.id = forum_posts.parent_id 
GROUP BY forum.id 
ORDER BY forum_posts.parent_id DESC, 
         forum_posts.time_created DESC 
LIMIT ?,?

我想告诉 ORDER BY 如果某个主题的 forum_posts.parent_id 中没有匹配项,则按forum.time_created排序。


附带说明一下,我还想知道如何将 WHERE 子句放入此查询中。我只想从论坛表"WHERE access <= ?"中获取行,但无法确定将该片段放在哪里

任何帮助非常感谢!


编辑:

目标是返回主题(从论坛表中)根据以下详细信息:

  1. 哪里 论坛.访问 <= ?
  2. 限制??
  3. 订购方式最新帖子 来自forum_posts表,forum.id 上匹配forum_posts.parent_id,或forum.time_created

编辑2:

一个包含相关数据的示例 SQL摆弄。这不起作用,因为订单实际上应该显示为 11,10,9,1,2http://sqlfiddle.com/#!2/83535/2

看看这个: http://sqlfiddle.com/#!2/be909/1

这是我的最后一个查询:

SELECT forum.*, recent_forum_posts.time_created as latest_post
FROM forum 
LEFT JOIN (SELECT MAX(forum_posts.time_created) as time_created, forum_posts.parent_id
           FROM forum_posts
           GROUP BY forum_posts.parent_id) AS recent_forum_posts
        ON forum.id = recent_forum_posts.parent_id 
WHERE forum.access > 2
ORDER BY recent_forum_posts.time_created IS NULL DESC,
         recent_forum_posts.time_created DESC,
         forum.time_created DESC 
LIMIT 5

本质上,子查询(LEFT JOIN 后面括号中的位)从forum_posts表中为每个parent_id选择最新的帖子。

然后左加入(因为我们想列出所有论坛,即使还没有帖子)。