1
我試圖從一組「帖子」中獲得最新的modified
「帖子」,它們都具有相同的parent_id
。我今天已經知道分組不是答案,我應該使用內部子查詢或「組內集合」,這要感謝this site >>集合>>集體內集合。我選擇去了最新的,因爲我覺得它更好,更容易實現因爲我使用CakePHP,並說要快(你能否證實?)如何在MySQL中進行組內聚合查詢?
於是我想出了以下查詢:
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');
兩個說明,請...你能提供你的表的一些示例數據? ...這個應用程序試圖爲用戶做什麼? – 2010-10-17 12:18:33
我編輯了我的問題。感謝您的關注。 – 2010-10-17 12:44:41
當你GROUP BY parentid時會發生什麼? – 2010-10-19 02:32:55