sql sum使用一对多关系

时间:2012-07-10 21:32:02

标签: mysql sum one-to-many

我有两张桌子

comments
------------------
id       text

rates
---------------------
id    comment_id    score

我的查询是...但总和操作不受影响。只有一行将会回归。

SELECT *, SUM(rates.score) FROM comment LEFT JOIN rate ON (rate.comment_id = comment.id)

3 个答案:

答案 0 :(得分:3)

SELECT comment.*, SUM(rates.score) FROM comment LEFT JOIN rate ON (rate.comment_id = comment.id)
GROUP BY comment.id

答案 1 :(得分:3)

您当前的查询只会将所有评论的评分相加。你必须做的是合并GROUP BY,它会按 每个 评论对聚合进行分组,因此SUM()的结果会 < em> only 是每个特定评论的评分总和:

SELECT a.*, SUM(b.score) AS ratingsum
FROM comment a
LEFT JOIN rate b ON a.id = b.comment_id
GROUP BY a.id

答案 2 :(得分:2)

尝试添加group by子句:

 SELECT comment.*, SUM(rates.score) FROM comment LEFT JOIN rate ON rate.comment_id = comment.id GROUP BY rates.comment_id;