如何在MySQL中进行组内聚合查询?

时间:2010-10-17 11:24:18

标签: mysql cakephp aggregate

我正在尝试从一组“帖子”中获取最新的modified个帖子,这些帖子都具有相同的parent_id。我今天已经知道分组不是答案,而且我应该使用内部子查询或“组内聚合”,这要归功于this site>>聚合>>组内聚合。我选择使用最新的,因为我发现它更好,更容易实现,因为我使用CakePHP,据说更快(你能确认吗?)

所以我提出了以下问题:

SELECT `Post`.`id`, `Post`.`parent_id`, `Post`.`modified` 
FROM `cake_posts` AS `Post` 
LEFT JOIN `cake_posts` AS `SelfPost` ON
      (`Post`.`id` = `SelfPost`.`id` AND `Post`.`modified` < `SelfPost`.`modified`)
WHERE `SelfPost`.`id` IS NULL 
ORDER BY `Post`.`parent_id` ASC

但结果如下:

|-----------------------------------|
| id |parent_id|      modified      |
|-----------------------------------|
| 1  |    1    |2010-10-16 17:04:43 |
| 3  |    1    |2010-10-16 20:04:53 |
| 6  |    2    |2010-10-16 21:46:59 |
| 5  |    2    |2010-10-16 21:46:44 |
| 2  |    2    |2010-10-16 17:06:10 |
| 4  |    4    |2010-10-16 21:46:19 |
| 7  |    7    |2010-10-16 22:03:19 |
| 8  |    8    |2010-10-16 22:03:25 |
| 9  |    9    |2010-10-16 22:03:32 |
| 10 |    10   |2010-10-17 00:18:10 |
| 11 |    11   |2010-10-17 00:18:15 |

正如你所看到的,我仍然有重复parent_id,所以我做错了什么?

编辑:基本上它只是一个非常轻量级的论坛,主题和帖子都存储在同一个表中。所以每个帖子(也就是消息,也就是表中的行)要么有不同的父母,要么自己作为父母(但我不认为这在这一点上是相关的)。我正在尝试构建索引,因此对于每个主题(即具有相同parent_id的帖子),我只想要最新修改的消息。我想得到的是:

|-----------------------------------|
| id |parent_id|      modified      |
|-----------------------------------|
|    |    -    |                    |
| 3  |    1    |2010-10-16 20:04:53 |
| 6  |    2    |2010-10-16 21:46:59 |
|    |    -    |                    |
|    |    -    |                    |
| 4  |    4    |2010-10-16 21:46:19 |
| 7  |    7    |2010-10-16 22:03:19 |
| 8  |    8    |2010-10-16 22:03:25 |
| 9  |    9    |2010-10-16 22:03:32 |
| 10 |    10   |2010-10-17 00:18:10 |
| 11 |    11   |2010-10-17 00:18:15 |

进一步的数据:

CREATE TABLE IF NOT EXISTS `cake_posts` (
  `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
  `parent_id` int(11) unsigned NOT NULL DEFAULT '0',
  `modified` datetime NOT NULL,
  PRIMARY KEY (`id`, `parent_id`),
  UNIQUE KEY `id_UNIQUE` (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 COMMENT='Posts to topics' AUTO_INCREMENT=12 ;

INSERT INTO `cake_posts` (`id`, `parent_id`, `modified`) VALUES
(1, 1, '2010-10-16 17:04:43'),
(3, 1, '2010-10-16 20:04:53'),
(6, 2, '2010-10-16 21:46:59'),
(5, 2, '2010-10-16 21:46:44'),
(2, 2, '2010-10-16 17:06:10'),
(4, 4, '2010-10-16 21:46:19'),
(7, 7, '2010-10-16 22:03:19'),
(8, 8, '2010-10-16 22:03:25'),
(9, 9, '2010-10-16 22:03:32'),
(10, 10, '2010-10-17 00:18:10'),
(11, 11, '2010-10-17 00:18:15');

1 个答案:

答案 0 :(得分:1)

好吧,经过多次尝试和挫折之后,我终于弄清楚出了什么问题。实际上是一个简单的错误,我加入了错误的领域。因为,因为我想最初分组By parent_id,所以我应该意识到我必须加入parent_id,而不是id。所以这是更正的查询:

SELECT `Post`.`id`, `Post`.`parent_id`, `Post`.`modified` 
FROM `cake_posts` AS `Post` 
LEFT JOIN `cake_posts` AS `SelfPost` ON
      (`Post`.`parent_id` = `SelfPost`.`parent_id` AND `Post`.`modified` < `SelfPost`.`modified`)
WHERE `SelfPost`.`id` IS NULL 
ORDER BY `Post`.`modified ` DESC
相关问题