Mysql 将行合并为一行,并根据id对行进行计数
我有三张桌子 post_表Mysql 将行合并为一行,并根据id对行进行计数,mysql,sql,Mysql,Sql,我有三张桌子 post_表 id_post | post_text 1 | great view 2 | happy breakfast 3 | good night everybody id_comment | comment_text | id_post 1 | that's amazing
id_post | post_text
1 | great view
2 | happy breakfast
3 | good night everybody
id_comment | comment_text | id_post
1 | that's amazing | 1
2 | of course, the best | 1
3 | wish me there | 1
4 | yes, happy breakfast | 2
5 | hehe | 2
注释表
id_post | post_text
1 | great view
2 | happy breakfast
3 | good night everybody
id_comment | comment_text | id_post
1 | that's amazing | 1
2 | of course, the best | 1
3 | wish me there | 1
4 | yes, happy breakfast | 2
5 | hehe | 2
附上图片
id_picture | picture_name | id_post
1 | pict_1 | 1
2 | pict_2 | 1
我想进行一个查询,使视图如下所示:
id_post | post_text | picture_name | comment_count
1 | great view | pict_1, pict_2 | 3
2 | happy breakfast | null | 2
3 | goodnight everybody | null | 0
select a.id_post, a.post_text, b.picture_name, count(c.id_comment) as comment_count
from post_table left join
attach_picture
on a.id_post=b.id_post left join
comment_table c
on a.id_post=c.id_post
group by a.id_post
我这样写查询:
id_post | post_text | picture_name | comment_count
1 | great view | pict_1, pict_2 | 3
2 | happy breakfast | null | 2
3 | goodnight everybody | null | 0
select a.id_post, a.post_text, b.picture_name, count(c.id_comment) as comment_count
from post_table left join
attach_picture
on a.id_post=b.id_post left join
comment_table c
on a.id_post=c.id_post
group by a.id_post
查询结果为:
id_post | post_text | picture_name | comment_count
1 | great view | pict_1 | 6
2 | happy breakfast | null | 2
3 | goodnight everybody | null | 0
结果是,picture\u name
只捕获1个picture\u name
即使是id\u post
也有超过1个picture\u name
,并且注释计数
显示picture\u name
的数量
有人能帮我解决问题吗?您可以随时修改您的查询以执行您想要的操作:
select pt.id_post, pt.post_text,
group_concat(distinct ap.picture_name) as picture_names,
count(distinct c.id_comment) as comment_count
from post_table pt left join
attach_picture ap
on pt.id_post = ap.id_post left join
comment_table c
on pt.id_post = c.id_post
group by pt.id_post;
这个查询所做的工作比它需要的要多,因为您正在沿着两个不同的维度连接帖子。因此,对于每一篇文章,您将得到所有评论和图像的笛卡尔积。如果你对一个给定的用户只有几条评论和帖子,那么这种方法就可以了。如果每个都有数千个,那么这可能会变得相当低效。在这种情况下,解决方案是在进行连接之前进行聚合
select a.id_post, a.post_text, GROUP_CONCAT(b.picture_name), (select count(id) from comment_table where id_post = a.id) as comment_count
from post_table a
left join attach_picture on a.id_post=b.id_post
left join comment_table c on a.id_post=c.id_post
group by a.id_post