将行连接成一个并根据id计算行

时间:2017-02-21 11:47:17

标签: mysql sql

我有3张桌子。

post_table

id_post | post_text                      
1       | great view                    
2       | happy breakfast           
3       | good night everybody 

comment_table

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

attach_picture

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        | 6  
2       | happy breakfast     | null          | 2  
3       | goodnight everybody | null          | 0  

结果是picture_name只抓住1 picture_name即使id_post有多个picture_namecomment_count也显示picture_name的数量} * comment_count

请有人帮我解决我的问题吗?

2 个答案:

答案 0 :(得分:2)

您可以随时修改查询以执行所需操作:

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;

此查询执行的工作量超出了需要,因为您要沿两个不同的维度加入帖子。因此,对于每个帖子,您将获得所有评论和图像的笛卡尔积。如果您只有一些给定用户的评论和帖子,那么这种方法很好。如果你有成千上万,那么这可能会相当低效。在这种情况下,解决方案是在进行连接之前进行聚合。

答案 1 :(得分:0)

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