2017-02-21 11 views
2

私は3つのテーブルを持っています。私が作りたい行を1に連結し、IDに基づいて行を数えよう

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 

結果はわずか1 picture_nameをキャッチpicture_nameですid_postであっても、picture_name以上であり、comment_countは、 * 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; 

このクエリを使用すると、2つの異なる次元に沿った投稿に参加しているので、それは、必要以上に仕事をしています。したがって、各投稿ごとに、すべてのコメントと画像のデカルト積が得られます。特定のユーザーのためのコメントと投稿が少ない場合、この方法は問題ありません。何千ものものがあれば、これはむしろ非効率的になる可能性があります。その場合、ソリューションは結合を行う前に集約することです。

+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 
関連する問題