我将如何将这个查询实现到我更复杂的查询中?
SELECT count(`p`.`id`) as count
FROM `wallPosts` `p` LEFT JOIN `wallPosts` `c` on `c`.`parentID` = `p`.`id`
where `p`.`parentID` is not null group by `p`.`parentID`
返回:
+-------+
| count |
+-------+
| 3 |
| 2 |
+-------+
我已将“复杂”查询简化为:
SELECT `p`.`id`,
`p`.`parentid`,
`p`.`commenterid`,
`p`.`userid`,
`p`.`post`,
`p`.`date`,
`p`.`tags`,
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`.`id`
LEFT JOIN `users`
ON `users`.`id` = `p`.`commenterid`
GROUP BY `p`.`id`
HAVING `ismain` = 'true'
ORDER BY `p`.`date` DESC
LIMIT 20
返回:
+----+----------+-------------+--------+--------+---------------------+------+--------+
| id | parentID | commenterID | userID | post | date | tags | isMain |
+----+----------+-------------+--------+--------+---------------------+------+--------+
| 5 | NULL | 1 | 1 | post#1 | 2013-07-26 13:29:02 | NULL | true |
| 1 | NULL | 1 | 1 | post#2 | 2013-07-26 13:28:23 | NULL | true |
+----+----------+-------------+--------+--------+---------------------+------+--------+
这就是我要的:
+----+----------+-------------+--------+--------+---------------------+------+--------+-------+
| id | parentID | commenterID | userID | post | date | tags | isMain | count |
+----+----------+-------------+--------+--------+---------------------+------+--------+-------+
| 5 | NULL | 1 | 1 | post#1 | 2013-07-26 13:29:02 | NULL | true | 3 |
| 1 | NULL | 1 | 1 | post#2 | 2013-07-26 13:28:23 | NULL | true | 2 |
+----+----------+-------------+--------+--------+---------------------+------+--------+-------+
这是我的完整表:
+----+----------+-------------+--------+---------+------+---------------------+
| id | parentID | commenterID | userID | post | tags | date |
+----+----------+-------------+--------+---------+------+---------------------+
| 1 | NULL | 1 | 1 | post#1 | NULL | 2013-07-26 13:28:23 |
| 2 | 1 | 1 | 1 | reply#1 | NULL | 2013-07-26 13:28:28 |
| 3 | 1 | 1 | 1 | reply#2 | NULL | 2013-07-26 13:28:38 |
| 4 | 1 | 1 | 1 | reply#3 | NULL | 2013-07-26 13:28:54 |
| 5 | NULL | 1 | 1 | post#2 | NULL | 2013-07-26 13:29:02 |
| 6 | 5 | 1 | 1 | reply#1 | NULL | 2013-07-26 13:29:05 |
| 7 | 5 | 1 | 1 | reply#2 | NULL | 2013-07-26 13:29:06 |
+----+----------+-------------+--------+---------+------+---------------------+
如您所见,我正在尝试计算每个帖子有多少回复。
谢谢你的帮助!