2017-02-21 65 views
2

我有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有多於1 picture_name,comment_count顯示金額picture_name * comment_count

請任何人都可以幫助我解決我的問題?

回答

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; 

此查詢做得比它需要更多的工作,因爲你是沿着兩個不同的維度加入職位。因此,對於每篇文章,您都可以獲得所有評論和圖片的笛卡爾產品。如果您對給定用戶只有幾條評論和帖子,那麼這種方法沒問題。如果每個人都有成千上萬的人,那麼這可能效率很低。在這種情況下,解決方案是在進行連接之前進行聚合。

+0

工作,謝謝 –

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