これは、選択と左結合で解決できます。
ごとに各テーブルのエントリをカウントするためpictureId
、pictures
テーブルは各リレーションの左側になります。それで:
select
p.id as pictureId,
count(distinct l.id) as count_likes,
count(distinct v.id) as count_views,
count(distinct c.id) as count_comments
from
pictures as p
left join likes as l on p.id = l.pictureId
left join views as v on p.id = v.pictureId
left join comments as c on p.id = c.pictureId
group by
p.id
基本的に、テーブル内の各レコードについて、各テーブル内のすべてのレコードをカウントしていpictures
ます。likes
、views
またはにレコードがない場合comments
、カウントはそれぞれゼロになります。
もちろん、このアイデアをコレクションに拡張することもできます。
select
c.id as collection_id,
p.id as picture_id,
count(distinct l.id) as count_likes,
count(distinct v.id) as count_views,
count(distinct c.id) as count_comments
from
collections as c
left join pictures as p on c.id = p.collection_id
left join likes as l on p.id = l.picture_Id
left join views as v on p.id = v.picture_Id
left join comments as c on p.id = c.picture_Id
group by
c.id,
p.id
コレクションごとに結果をフィルタリングする場合は、where c.id = aValue
前に追加するだけで済みます(取得するコレクションIDはgroup by
どこにありますか)。aValue
これがお役に立てば幸いです。
各コレクションの集計データのみが必要な場合:
select
c.id as collection_id,
count(distinct l.id) as count_likes,
count(distinct v.id) as count_views,
count(distinct c.id) as count_comments
from
collections as c
left join pictures as p on c.id = p.collection_id
left join likes as l on p.id = l.picture_Id
left join views as v on p.id = v.picture_Id
left join comments as c on p.id = c.picture_Id
group by
c.id
これでうまくいくはずです;-)