我一直在研究这个问题的时间比我承认的要长。任何帮助将不胜感激!
我正在制作一个带回复的基本评论系统(限于一个级别)。
我使用的模型非常自我解释。
如您所见,
当commenterID
和userID
相等而且parentID
为空时,它将是“状态更新”,应该在主页上显示。这是父母。
我需要在首页上包含父作品的每个回复(返回isMain为true)。
在我的示例中,ID 1是父状态更新,ID 3,4是对ID 1的回复。
通过转储一些数据来解释我的问题会更容易:
CREATE TABLE `wallPosts` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`parentID` int(11) DEFAULT NULL,
`commenterID` varchar(255) NOT NULL,
`userID` varchar(255) DEFAULT NULL,
`post` text,
`tags` varchar(255) DEFAULT NULL,
`date` datetime NOT NULL,
PRIMARY KEY (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=latin1 AUTO_INCREMENT=7 ;
--------------------------------------------------------
INSERT INTO `wallPosts` VALUES(1, NULL, '1', '1', 'This is a status update', NULL, '2013-07-23 08:34:28');
INSERT INTO `wallPosts` VALUES(3, 1, '1', '1', 'this is a reply to a status update', NULL, '2013-07-23 08:35:39');
INSERT INTO `wallPosts` VALUES(4, 1, '2', '1', 'this is a reply to the status update from another user', NULL, '2013-07-15 11:57:35');
INSERT INTO `wallPosts` VALUES(5, NULL, '1', '2', 'This is a post on a user\\''s wall, should not be displayed on main page', NULL, '2013-07-23 08:37:28');
INSERT INTO `wallPosts` VALUES(6, 5, '1', '2', 'this is a reply to a wall post, should not be displayed on main', NULL, '2013-07-23 08:37:44');
这就是我目前所拥有的:
这就是我想要的:
这是我一直在使用的查询:
SELECT
`p`.`id`,
`p`.`parentID`,
`p`.`commenterID`,
`p`.`userID`,
`p`.`post`,
case
when (`p`.`userID` = `p`.`commenterID` and `p`.`parentID` IS NULL)
then 'true'
else 'false'
end as isMain
FROM `wallPosts` `p`
LEFT JOIN `wallPosts` `c` ON `c`.`parentID` = `p`.`parentID` AND `c`.`id` > `p`.`id`
GROUP BY `p`.`id`, `p`.`parentID`
HAVING COUNT(`c`.`id`) < 10
这限制了最近10次回复的数量。
感谢您的帮助! :)
答案 0 :(得分:1)
尝试以下方法。参考sqlfiddle链接。 http://sqlfiddle.com/#!2/2b731/8
选择
`p`.`id`,
`p`.`parentID`,
`p`.`commenterID`,
`p`.`userID`,
`p`.`post`,
case
when (`p`.`userID` = `p`.`commenterID` and `p`.`parentID` IS NULL) or parentid in (select id from wallPosts where parentid is null and commenterid=userid)
then 'true'
else 'false'
end as isMain
FROM `wallPosts` `p` limit 10;
根据您的要求我正在更改您的SQL查询
SELECT
`p`.`id`,
`p`.`parentID`,
`p`.`commenterID`,
`p`.`userID`,
`p`.`post`,
case
when (`p`.`userID` = `p`.`commenterID` and `p`.`parentID` IS NULL) or p.parentid in (select id from wallPosts where parentid is null and commenterid=userid)
then 'true'
else 'false'
end as isMain
FROM `wallPosts` `p`
LEFT JOIN `wallPosts` `c` ON `c`.`parentID` = `p`.`parentID` AND `c`.`id` > `p`.`id`
GROUP BY `p`.`id`, `p`.`parentID`
HAVING COUNT(`c`.`id`) < 10