[英]Ordering By Another Table Column If Exists
我将一个带有主题/帖子的简单论坛脚本组合在一起。 我正在尝试按最新帖子排序主题,但以下问题的答案让我有些运气: MYSQL从另一个Table排序,但是我遇到的问题是某些主题还没有任何帖子,因此查询根本不会选择这些主题。
当前编码为:
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访问<=?”,但不能制定出在哪里把该片断英寸
任何帮助,不胜感激!
编辑:
目标是返回主题(从论坛表中)根据以下详细信息:
编辑2:
一个带有相关数据的示例SQLfiddle。 这是行不通的,因为该命令实际上应为11,10,9,1,2 http://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
括号中的位)从forum_posts
表中为每个parent_id
选择最新的帖子。
那就是LEFT JOINed(因为我们想要列出所有论坛的,即使还没有帖子)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.