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

标签 php mysql

当我有两个表时如何显示最新的帖子,这两个表都包含名为 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/

相关文章:

php - 错误 : utf8_mime2text() has new signature, 但缺少 U8T_CANONICAL

php - 在 MySQL 中查询非转义字符串

php - 如何根据字段对MySQL结果进行分组

php - 将普通的 SELECT 查询转换为准备好的 SELECT 查询

php - 喜欢/不喜欢像 FB 这样的系统

php - jquery ajax调用不是异步的

php - 如何选择具有相同唯一外国ID的最新记录?

php - 创建 PHPUnit 模拟模型使用默认数据库而不是 CakePHP 中的测试

python - mysql - 如何在 mysql 中存储 python 列表对象?

java - 将现有对象的值添加到 JTable?