我有三种表格类型,帖子和见解。
这是我的sql fiddle SQL Fiddle的链接。
现在我要生成一个报告,其中包含针对每种类型的帖子数量以及他们喜欢和评论的总和,即类型| COUNT(post_id)| SUM(喜欢)| SUM(注释)。
这些是我的尝试:
select type_name, count(p.post_id), sum(likes), sum(comments)
from types t
left join posts p on t.type_id = p.post_type
left join insights i on p.post_id = i.post_id
group by type_name;
结果:汇总值不正确。
select type_name, count(p.post_id), p.post_id,
(select sum(likes) from insights where post_id = p.post_id) as likes,
(select sum(comments)from insights where post_id = p.post_id) as comments
from types t
left join posts p on t.type_id = p.post_type
group by type_name;
结果:仅显示一个帖子的赞和评论总和。
答案 0 :(得分:3)
你的第一次尝试真的很接近。但每个post_id
乘以insights
中的匹配数,因此您需要使用DISTINCT
:
select type_name, count(distinct p.post_id), sum(likes), sum(comments)
from types t
left join posts p on t.type_id = p.post_type
left join insights i on p.post_id = i.post_id
group by type_name;
或者,您可以使用子查询进行分组,该子查询结合了同一帖子的所有见解:
select type_name, count(*), sum(likes), sum(comments)
from types t
left join posts p on t.type_id = p.post_type
left join (select post_id, sum(likes) likes, sum(comments) comments
from insights
group by post_id) i on p.post_id = i.post_id
group by type_name;
答案 1 :(得分:-1)
试试这个
SELECT types.type_name, stats.posts, stats.likes, stats.comments
FROM types
LEFT JOIN (
select post_type, count(i.post_id) as posts, sum(i.likes) as likes, sum(i.comments) as comments
from insights i INNER JOIN posts p ON i.post_id = p.post_id
) as stats
ON types.type_id = stats.post_type;