如何在查询中将限制应用于此父/子树(如表)

时间:2011-12-15 21:19:08

标签: mysql sql

这是表结构:

CREATE TABLE `message` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `uid` int(11) NOT NULL,
  `from_uid` int(11) NOT NULL,
  `content` varchar(300) NOT NULL,
  `parent` int(11) DEFAULT NULL,
  `create_time` datetime NOT NULL,
  PRIMARY KEY (`id`),
  KEY `uid` (`uid`),
  KEY `from_uid` (`from_uid`),
  KEY `parent` (`parent`),
  CONSTRAINT `message_ibfk_1` FOREIGN KEY (`uid`) REFERENCES `u
ser` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `message_ibfk_2` FOREIGN KEY (`from`) REFERENCES `user
` (`id`) ON DELETE CASCADE ON UPDATE CASCADE,
  CONSTRAINT `message_ibfk_3` FOREIGN KEY (`parent`) REFERENCES `message` (`id`) ON DELETE CASCADE ON UPDATE CASCADE
) ENGINE=InnoDB AUTO_INCREMENT=20 DEFAULT CHARSET=utf8 |

这是一个存储用户消息及其回复的表。如果我对整个查询应用限制,让我们说限制30,结果将是包含父消息和子消息(回复)的30行。但是如何在每条消息的回复中获得30条父消息?

1 个答案:

答案 0 :(得分:0)

试试这个:

SELECT `message`.* 
FROM 
        `message` INNER JOIN
        (SELECT `id` FROM `message` WHERE `parent` IS NULL LIMIT 30) `ids` ON 
            `message`.`id` = `ids`.`id` OR `message`.`parent` = `ids`.`id`