三个表连接并计数显示错误的结果

时间:2016-07-13 11:31:32

标签: mysql sql join left-join

我有3个表,我需要从目录中获取所有信息,加入评级表并加入评论表,然后按目录帖子计算评论,我的SQL查询:

SELECT
    catalog.catalog_id,
    catalog.slug,
    catalog.title,
    catalog.city,
    catalog.street,
    catalog.image COUNT(ratings.rate) AS votes,
    COUNT(comments.catalog_id) AS total_comments,
    ROUND(SUM(ratings.rate) / COUNT(ratings.rate)) AS average
FROM
    catalog
LEFT JOIN ratings ON ratings.object_id = catalog.catalog_id
LEFT JOIN comments ON comments.catalog_id = catalog.catalog_id
GROUP BY
    catalog.catalog_id
ORDER BY
    average,
    votes DESC

一切都显示罚款只有total_comments坏数字6,但在评论表中只有2行,所以结果不好。我认为这是分组的问题。我尝试添加GROUP BY catalog.catalog_id, comments.catalog_id,但没有帮助。 我的桌子:

enter image description here

1 个答案:

答案 0 :(得分:2)

问题在于您有多个评分和评论,因此每个帖子都会获得一个笛卡尔积。

正确的解决方案是在加入前预先汇总数据。

SELECT c.*, r.votes, c.total_comments,
       ROUND(sumrate / votes) AS average
FROM catalog c LEFT JOIN
     (SELECT r.object_id, COUNT(*) as votes, SUM(r.rate) as sumrate
      FROM ratings r
      GROUP BY r.object_id
     ) r
     ON r.object_id = c.catalog_id LEFT JOIN
     (SELECT c.catalog_id, COUNT(*) as total_comments
      FROM comments c
      GROUP BY c.catalog_id
     ) c
     ON c.catalog_id = c.catalog_id
GROUP BY c.catalog_id
ORDER BY average, votes DESC;