您可以使用选择和左连接来解决此问题。
由于您将计算每个表上的条目 every 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
之前添加group by
(aValue
你要检索的集合Id在哪里)
希望这对您有所帮助。
如果您只需要每个集合的聚合数据:
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
这应该可以解决问题;-)