Php 如何选择具有最新日期时间的标题?

Php 如何选择具有最新日期时间的标题?,php,mysql,Php,Mysql,我在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_中,标题和post_内容可以是一个

我在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_中,标题和post_内容可以是一个post id的多个条目

我需要的是选择具有最新日期时间的标题。我必须使用posts id选择所有内容。我如何才能做到这一点


编辑:我需要同时选择最新标题和最新内容,或者选择最新标题、最新内容和最新状态。

在这种情况下,按您感兴趣的列datetime排序,并限制为1。这将按日期时间按降序排列行,最新的将排在第一位。然后限制为1,以获得第一行

SELECT * FROM post_titles ORDER BY datetime DESC LIMIT 1;

在本例中,按您感兴趣的datetime列排序,并限制为1。这将按日期时间按降序排列行,最新的将排在第一位。然后限制为1,以获得第一行

SELECT * FROM post_titles ORDER BY datetime DESC LIMIT 1;

基于Mark S的答案,我不知道如何引用或链接到他的答案

由于post_title和post_contents表上都有datetime字段,因此在排序时必须指定要引用的表的列,如下所示:

选择'title','content` 从'post_titles't 使用'post\u id'加入'post\u contents'c` 按t.datetime描述订购 限制1
基于Mark S的答案,我不知道如何引用或链接到他的答案

由于post_title和post_contents表上都有datetime字段,因此在排序时必须指定要引用的表的列,如下所示:

选择'title','content` 从'post_titles't 使用'post\u id'加入'post\u contents'c` 按t.datetime描述订购 限制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);
我假设所有的datetime都是相等的,因为当您在表上添加内容时,内容是同时创建的

编辑:现在不管日期时间是否相等。检查它是否有效。

试试这个:

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);
我假设所有的datetime都是相等的,因为当您在表上添加内容时,内容是同时创建的


编辑:现在不管日期时间是否相等。检查它是否有效。

使用maxdatetime和group by post\u id获取该帖子的最大日期时间。。。将它连接回带有post_id的标题,max datetimesomeone问,然后删除一条评论,这不是很慢吗?我的回答是:不知道。这可能取决于这里没有给出的全部信息…使用maxdatetime和group by post_id来获取该帖子的最大日期时间。。。将它连接回带有post_id的标题,max datetimesomeone问,然后删除一条评论,这不是很慢吗?我的回答是:不知道。这可能取决于此处未给出的全部信息…使用联接添加获取post_contentsWorst案例,执行子选择:从所有表中选择所有内容,其中id在select id from post_titles ORDER BY datetime DESC LIMIT 1使用联接添加获取post_contentsWorst案例,执行子选择:从所有表中选择所有内容,其中id在select id from post_titles ORDER BY datetime DESC LIMIT 1Yes中,因为查询结束时的限制为1,因此这将只提供标题最近更新的文章。这是我以为你想要的,标题是最新的datetime。如果您想要的内容不止这些,或者基于其中一个标题的最新时间的多篇文章内容,那么Mark S.评论中的子选择方法是最好的方法。是的,由于查询末尾的限制1,这将只提供标题最近更新的文章。这是我以为你想要的,标题是最新的datetime。如果你想要更多的东西,或者基于其中一个标题的最新时间的多个帖子内容,那么Mark S.评论中的子选择方法是最好的方法。