gpt4 book ai didi

php - 根据日期获取最新的帖子

转载 作者:行者123 更新时间:2023-11-29 04:59:32 26 4
gpt4 key购买 nike

当我有两个表时如何显示最新的帖子,这两个表都包含名为 creation_date 的列

如果我所要做的只是根据 posts created_on 值获取最新的帖子,这将很简单,但是如果帖子包含回复,我需要将其纳入等式。如果帖子有更新的回复,我想获取回复 created_on 值,但也获取帖子 post_id 和主题。

posts 表结构:

CREATE TABLE `posts` (
`post_id` bigint(20) unsigned NOT NULL auto_increment,
`cat_id` bigint(20) NOT NULL,
`user_id` bigint(20) NOT NULL,
`subject` tinytext NOT NULL,
`comments` text NOT NULL,
`created_on` datetime NOT NULL,
`status` varchar(10) NOT NULL default 'INACTIVE',
`private_post` varchar(10) NOT NULL default 'PUBLIC',
`db_location` varchar(10) NOT NULL,
PRIMARY KEY (`post_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;

回复表结构:

CREATE TABLE `replies` (
`reply_id` bigint(20) unsigned NOT NULL auto_increment,
`post_id` bigint(20) NOT NULL,
`user_id` bigint(20) NOT NULL,
`comments` text NOT NULL,
`created_on` datetime NOT NULL,
`notify` varchar(5) NOT NULL default 'YES',
`status` varchar(10) NOT NULL default 'INACTIVE',
`db_location` varchar(10) NOT NULL,
PRIMARY KEY (`reply_id`)
) ENGINE=MyISAM DEFAULT CHARSET=latin1 AUTO_INCREMENT=5 ;

到目前为止,这是我的查询。我已经删除了提取日期的尝试。

$strQuery = "SELECT posts.post_id, posts.created_on, replies.created_on, posts.subject ";
$strQuery = $strQuery."FROM posts ,replies ";
$strQuery = $strQuery."WHERE posts.post_id = replies.post_id ";
$strQuery = $strQuery."AND posts.cat_id = '".$row->cat_id."'";

最佳答案

$strQuery = "
SELECT posts.post_id, GREATEST(posts.created_on, replies.created_on) AS latestDate, posts.subject
FROM posts, replies
WHERE posts.post_id = replies.post_id
AND posts.cat_id = {$row->cat_id}
GROUP BY posts.post_id
ORDER BY latestDate DESC;
";

更新:再看一遍,上面的内容实际上是不正确的,因为它不包括那些还没有任何回复的帖子。更正确的做法是:

$strQuery = "
SELECT posts.post_id, GREATEST(posts.created_on, replies.created_on) AS latestDate,
FROM posts
LEFT JOIN replies ON (posts.post_id = replies.post_id)
WHERE posts.cat_id = {$row->cat_id}
GROUP BY posts.post_id
ORDER BY latestDate DESC
LIMIT 0,1;
";

关于php - 根据日期获取最新的帖子,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2816936/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com