我有三个表存储桶(类别),帖子,评论 而且我想获得具有15条以上评论的类别中的帖子数
我正在尝试以下查询:
SELECT buckets.`id`,buckets.`name`,COUNT(comment.`post_id`) AS comment_count
FROM post
LEFT JOIN `comment` ON comment.`post_id` = post.`id`
INNER JOIN `buckets` ON buckets.`id` = post.`bucket`
GROUP BY comment.`post_id`
HAVING COUNT(buckets.`id`) > 14 ORDER BY buckets.`id`
预期结果
+----+---------+------------+---------------+
| ID | NAME | POST_COUNT | COMMENT_COUNT |
+----+---------+------------+---------------+
| 1 | Bucket1 | 3 | 70 |
+----+---------+------------+---------------+
| 2 | Bucket2 | 2 | 80 |
+----+---------+------------+---------------+
| 3 | Bucket3 | 4 | 90 |
+----+---------+------------+---------------+
| 4 | Bucket4 | 0 | 15 |
+----+---------+------------+---------------+
答案 0 :(得分:0)
我想获得包含15条以上评论的类别中的帖子数
您的问题表达不佳。将来请记住,如果表有明确说明,则回答表的问题会更容易。
很明显,您对帖子有评论。让我们得到15个或更多的那些。 (您说的是“大于15”,但是查询要求输入> 14
。
select post_id, count(*) as ncomment from comments
group by post_id
having count(*) > 14
现在我们可以按类别对帖子进行计数,并获得每个帖子的评论总数
select category, count(P.post_id) as npost, sum(N) as ncomment
from from buckets as P
join (
select post_id, count(*) as N
from comments
group by post_id
having count(*) > 14
) as C
on P.post_id = C.post_id
group by category
答案 1 :(得分:0)
我得到的查询不完全是我想要的,但使用group_concat有用
SELECT A.id,A.name,GROUP_CONCAT(A.comment_count SEPARATOR',')AS total_post FROM(SELECT buckets.id,buckets.name,
COUNT(comment.post_id)AS comment_count FROM post INNER JOIN comment
ON comment.post_id = post.id
内连接桶在buckets.id = post.bucket上
GROUP BY comment.post_id拥有COUNT(comment.post_id)> 14)A GROUP BY A.id,A.name
注意-> total_post是超过14条评论的帖子
id ----名称----- total_post
1 ---- H1B ------ 91、15、19、20、15、15、26、20、79
3 ---- I-140----- 28
4 ---- I-134(AP)----- 40,28,62
7 ---- MISC -------- 74,15