通过帖子获取总计数和评论

时间:2017-10-08 17:47:32

标签: mysql sql

我想在联接的帮助下,在单个查询中获得每个帖子的总喜欢和总数。

我正在使用此查询。但结果是错误的

SELECT blog.id, count(blog_comments.id) as likes , count(blog_likes.id) as comments
FROM blog LEFT JOIN
     blog_comments
     ON blog.id = blog_comments.blog_id LEFT JOIN
     blog_likes
     ON blog.id = blog_likes.blog_id 
GROUP BY blog.id

请检查图像的表格结构:

2 个答案:

答案 0 :(得分:2)

您的问题是您正在同时聚合两个维度。生成一个笛卡尔积 - 每行与每个注释一对,总共l * c行。

解决此问题的最简单方法是使用DISTINCT关键字:

SELECT b.id, count(DISTINCT bl.id) as likes , count(DISTINCT bc.id) as comments
FROM blog b LEFT JOIN
     blog_comments bc
     ON b.id = bc.blog_id LEFT JOIN
     blog_likes
     ON b.id = bl.blog_id 
GROUP BY b.id;

如果您的帖子有很多喜欢和很多评论,建议不要这样做,因为它会创建两者的笛卡尔积。

有几个解决方案,但我建议使用相关子查询:

select b.id,
       (select count(*) from blog_likes bl where bl.blog_id = b.id) as likes,
       (select count(*) from blog_comments bc where bc.blog_id = b.id) as comments
from blogs b;

这可以利用blog_likes(blog_id)blog_comments(blog_id)上的索引。

答案 1 :(得分:0)

这是根据我的表格它会帮助你...

SELECT people.pe_name,COUNT(distinct orders.ord_id)AS num_orders,COUNT(items.item_id)AS num_items FROM people INNER JOIN orders ON orders.pe_id = people.pe_id INNER JOIN items ON items.ord_id = orders.ord_id GROUP BY people.pe_id;