当我有两张表时,如何显示最近的帖子,这两张表都包含一个名为 creation_date 的列
如果我所要做的就是根据创建的帖子获取最新的帖子,这将很简单,但如果帖子包含回复,我需要将其纳入等式。 如果帖子有更新的回复,我想获得created_on值的回复,但也获得帖子post_id和subject。
帖子表格结构:
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."'";
答案 0 :(得分:3)
$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;
";
答案 1 :(得分:1)
SELECT posts.post_id,posts.subject,replies.post_id
来自帖子 LEFT JOIN回复ON post.post_id = replies.post_id
WHERE posts.cat_id ='$ row-> cat_id'
ORDER BY posts.post_id DESC,replies.post_id DESC
没有回复的那个将返回NULL,您可以在输出中使用PHP过滤掉。
答案 2 :(得分:0)
获取最新帖子,对帖子的最新回复,然后获取最新的帖子。
这使用order by created_on desc limit 1
仅从表中获取最后一项。
我建议在两个表的created_on
列上添加密钥,在回复表中为post_id
列添加密钥。
更新:cat_id
也需要建立索引。
select * from (
select * from
(
select p.post_id, p.created_on , 'post' as post_type
from posts p
where p.cat_id = '$row->cat_id'
order by p.created_on desc limit 1
)post
union
select * from
(
select p.post_id, r.created_on , 'reply'
from posts p
inner join replies r on r.post_id = p.post_id
where p.cat_id = '$row->cat_id'
order by r.created_on desc limit 1
)reply
)big order by big.created_on limit 1;