MySQL总和,计数与分组和连接

时间:2013-12-24 07:45:21

标签: mysql select join group-by aggregate-functions

我有三种表格类型,帖子和见解。

  • 类型表包含帖子的类型。
  • 帖子表包含已发布的帖子。
  • 洞察力表包含每日帖子的见解。

这是我的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;

结果:仅显示一个帖子的赞和评论总和。

2 个答案:

答案 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;

FIDDLE

答案 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;