[英]How to select the title with the latest datetime?
我在mysql中有以下两个表:
posts (id)
post_titles (id, post_id, title, datetime, user_id)
post_contents (id, post_id, content, datetime, user_id)
post_statuses (id, post_id, status, datetime, user_id)
posts (id) == posts_titles (post_id)
在post_titles
和post_contents
可以是1 posts (id)
多个条目。
我需要的是选择具有最新日期时间的标题。 我必须使用posts (id)
来全部选择。 我该怎么办?
编辑:我需要选择最新的标题和最新的内容一起或最新的标题,最新的内容和最新的状态。
按感兴趣的列排序(在这种情况下为datetime),限制为1。这将按datetime的降序对行进行排序(最新的排在第一位)。 然后将1限制为仅获得第一行。
SELECT * FROM post_titles ORDER BY datetime DESC LIMIT 1;
尝试这个:
SELECT t.title, c.content
FROM post_titles t
JOIN post_contents c ON t.post_id = c.post_id
WHERE
t.datetime =
(SELECT MAX(x.datetime) FROM post_titles x WHERE t.post_id = x.post_id)
AND
c.datetime =
(SELECT MAX(y.datetime) FROM post_contents y WHERE c.post_id = y.post_id);
我假设所有日期时间都是相等的,因为当您在表上添加内容时,将同时创建内容。
编辑:现在日期时间是否相等都没有关系。 检查它是否有效。
以Mark S的答案为基础(我不知道如何引用或链接到他的答案...)
由于post_title
和post_contents
表上都有datetime
字段,因此post_title
排序时必须指定要引用的表列,如下所示:
SELECT `title`, `content`
FROM `post_titles` t
JOIN `post_contents` c USING (`post_id`)
ORDER BY t.datetime DESC
LIMIT 1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.