简体   繁体   English

SQL:与另一个表中的最新行联接

[英]SQL: Join with most recent row in another table

I'm trying to build a simple forum as a learning exercise. 我正在尝试建立一个简单的论坛作为学习练习。 At the moment I have a topics(questions) table and a posts table (where the post_thread_id refers to the topic id). 目前,我有一个topic(questions)表和一个posts表(其中post_thread_id表示主题ID)。

I want to display the topics in the order by which the most recent post in that topic appears. 我想按该主题中最新帖子的显示顺序显示主题。 Looking online I used this command: 在线查看时,我使用了以下命令:

SELECT topics.topic_title, topics.topic_date, topics.topic_title, max( posts.post_date )
FROM topics
LEFT OUTER JOIN posts ON topics.topic_id = posts.post_thread_id
GROUP BY topics.topic_id
ORDER BY MAX( posts.post_id ) ASC

which seems to work. 这似乎有效。 But it doesn't work if there are no posts linked to a topic (ie an empty topic) as NULL comes first every time. 但是,如果没有帖子链接到某个主题(例如,一个空主题),这将不起作用,因为每次都会出现NULL。 I want it so that if no posts exist then the topic date is used to order. 我想要这样,如果不存在帖子,则使用主题日期进行排序。

How do I select the topic date if there are no posts? 如果没有帖子,如何选择主题日期?

Thanks (I'd appreciate a simple explanation as to how it is working as I am trying to learn). 谢谢(我很想简单地解释一下它在尝试学习时的工作原理)。

ORDER BY 
CASE WHEN MAX( posts.post_id ) IS NULL THEN 1 ELSE 0 END ASC

Self explanatory,when MAX(post_Id) is null it will change the order priority. 不言自明,当MAX(post_Id)为null时,它将更改顺序优先级。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM