他们上一个版本的所有帖子

时间:2011-10-11 13:41:42

标签: mysql

在我的数据库中,我必须显示所有帖子及其最后内容的预览,我真的不知道该怎么做。

CREATE TABLE IF NOT EXISTS `posts` (
`id` int(11) NOT NULL auto_increment,
`post_id` int(11) NOT NULL,
`title` varchar(255) NOT NULL,
`body` text NOT NULL,
`created` date NOT NULL,
PRIMARY KEY  (`id`),
KEY `post_id` (`post_id`)) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=4 ;

INSERT INTO `posts` (`id`, `post_id`, `title`, `body`, `created`) VALUES 
(1, 1, 'hello world', 'this is the first post', '2011-10-10'), 
(2, 2, 'the second post', 'and this is the second post', '2011-10-10'), 
(3, 2, 'second post', 'title is modified, this is a better version', '2011-10-11');

所以结果必须是id为1和3的帖子。第二篇文章出现两次,因为在不同的日期有两个版本。帖子的日期标记哪个版本更新。

我需要显示所有帖子的最后状态。我怎么能这样做?

2 个答案:

答案 0 :(得分:1)

这个怎么样?正在使用ID来判断哪个更新。

SELECT id, post_id, title, body, created
FROM posts 
WHERE (post_id, id) IN (SELECT post_id, MAX(id) FROM posts GROUP BY post_id)

如果您需要使用日期(如果同一天有两个帖子怎么办?)

SELECT id, post_id, title, body, created
FROM posts 
WHERE (post_id, created) IN (SELECT post_id, MAX(created) FROM posts GROUP BY post_id)

答案 1 :(得分:1)

这是每组前N个问题:

您将如何做到这一点:

SELECT A.* FROM (
    SELECT 
        p.*,
        IF( @p <> ID, @n := 1, @n := @n+1 ) AS r, 
        @p := post_id
    FROM
        posts p
    ORDER BY post_id, created DESC
    ) AS A
WHERE r = 1

了解更多信息: http://www.artfulsoftware.com/infotree/queries.php#104

说明:

SELECT A.* FROM (
    SELECT 
        p.*,
        IF( 
                @p <> ID,   /* check if this record is a new post_id */
                @n := 1,    /* if it is a new post_id, reset the counter to 1 */
                @n := @n+1  /* other wise, increment the counter */
            ) AS r,
        @p := post_id   /* assign the post_id of this record to @p to use in the IF statement */
    FROM
        posts p
    ORDER BY 
        post_id,     /*first, order by postID so we scan over all versions of posts together */
        created DESC /* then order by createDate DESC so the newest versions of each post are first */
    ) AS A
WHERE r = 1

(子查询的)样本结果:

id | post_id | title | body | created    | r | @p
1  | 1       | ...   | ...  | 10/10/2011 | 1 | 1
3  | 2       | ...   | ...  | 10/11/2011 | 1 | 2
2  | 2       | ...   | ...  | 10/10/2011 | 2 | 2