1

好吧,我有两张表 community 和 community_comments。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;   

任何帮助将不胜感激。谢谢。

4

2 回答 2

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

如果您不想显示没有评论的社区,您可以将左外连接替换为内连接。

于 2012-06-30T13:54:26.023 回答
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 ;
于 2012-06-30T15:45:13.157 回答