我有 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
但没有帮助。
我的桌子:
问题是您有多个评分和评论,因此每个帖子都会得到一个笛卡尔积。
正确的解决方案是在加入之前预先聚合数据。
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;
是否可以在没有子查询的情况下做到这一点