MySQL JOIN通过比较发布日期和评论日期来提取最新帖子

时间:2012-06-30 13:32:03

标签: mysql group-by

好吧,我有两个表社区和社区评论。 community是存储主题标题和主题的其他详细信息的表。 community_details是存储主题/线程的所有帖子或评论的表。

我需要根据线程的评论日期以及原始主题/主题的日期来提取最新的五个主题。

现在可能还有一些线程没有任何评论,但是比一些有评论的线程更新。我需要正确地把它们拉出来。

我尝试了诸如

之类的查询
SELECT MAX(community_comments.id), `community`.*
FROM (`community`)
LEFT JOIN `community_comments` ON `community`.`id`=`community_comments`.`community_id`
WHERE `community`.`type` = 1
GROUP BY `community_comments`.`id`
ORDER BY `community_comments`.`date_posted` DESC
LIMIT 5 

这多次拉出同一个线程,这个

SELECT MAX(community_comments.id), `community`.*
FROM (`community`)
LEFT JOIN `community_comments` ON `community`.`id`=`community_comments`.`community_id`
WHERE `community`.`type` = 1
GROUP BY `community_comments`.`community_id`
ORDER BY `community_comments`.`date_posted` DESC
LIMIT 5 

提取独特的线程,但不会提取正确的最新线程。

社区的表格结构是:

CREATE TABLE `community` (   
  `id` varchar(12) character set utf8 NOT NULL,   
  `title` varchar(255) character set utf8 NOT NULL,   
  `content` text character set utf8 NOT NULL,   
  `author` varchar(13) character set utf8 NOT NULL,   
  `category` int(10) unsigned NOT NULL,   
  `type` tinyint(1) unsigned NOT NULL default '1' COMMENT '1 = Forum; 2 = Site Help; 3 = Local & Global',   
  `location` varchar(100) character set utf8 NOT NULL,   
  `country` int(10) unsigned NOT NULL,   
  `date_posted` datetime NOT NULL,   
  PRIMARY KEY  (`id`)   
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;   

和community_comments的表结构是:

CREATE TABLE `community_comments` (   
  `id` varchar(12) character set utf8 NOT NULL,   
  `community_id` varchar(12) character set utf8 NOT NULL,   
  `content` text character set utf8 NOT NULL,   
  `member_id` varchar(13) character set utf8 NOT NULL,   
  `type` tinyint(1) unsigned NOT NULL default '1' COMMENT '1 = Forum; 2 = Site Help; 3 =  Local & Global',   
  `quoted` varchar(12) character set utf8 NOT NULL COMMENT 'Id number of the comment that is being quoted',   
  `date_posted` datetime NOT NULL,   
  PRIMARY KEY  (`id`)   
) ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;   

非常感谢任何帮助。感谢。

2 个答案:

答案 0 :(得分:2)

因此,如果我理解正确,您需要社区字段,其中包含5个最新的community_comments。您希望使用SQL Group By来实现此目的。

SELECT c.*, MAX(com.date_posted) as last_post
FROM community c
LEFT OUTER JOIN community_comments com
ON com.community_id = c.id
GROUP BY c.id
ORDER BY MAX(com.date_posted) DESC
LIMIT 5

如果您不想显示没有评论的社区,可以使用内部联接替换左外部联接。

答案 1 :(得分:0)

SELECT c.*, IFNULL(MAX(com.date_posted),c.date_posted) as last_post 
            FROM community c 
            LEFT OUTER JOIN community_comments com 
            ON com.community_id = c.id 
            GROUP BY c.id 
            ORDER BY last_post DESC 
            LIMIT 5 ;