Mysql SUM输出错误

时间:2011-08-19 12:13:21

标签: mysql count sum left-join

我有一个类似的查询:

SELECT DISTINCT
g.thumb, h.hotel_name, h.id, COUNT(c.id) as total_comments, SUM(c.rating) AS total_ratings
FROM 
at_hotels h 
LEFT JOIN 
at_gallery g 
ON 
h.id = g.h_id
LEFT OUTER JOIN
at_comments c
ON
h.id = c.h_id AND c.status = '1'
GROUP BY h.id 
ORDER BY h.id DESC LIMIT 5

查询正在工作,但SUM(评级)除外。 Sum命令给出的超过预期。我也试过像这样的SUM命令:

--query
(SELECT SUM(rating) FROM at_comments WHERE at_comments.h_id = at_hotels.id) AS total
--more query

这也不行。

总数必须是:13,但这是给出36.问题在哪里?

样本数据:(评论表)

id h_id rating
----------
1 | 1  |5
----------
2 | 1  |3
----------
3 | 1  |5

我的表格:

Tables

3 个答案:

答案 0 :(得分:0)

这完全取决于您的数据(我们看不到),但我建议不要依赖MySQL为您的分组做“正确的事”,而是明确GROUP BY它们:

SELECT 
MAX(g.thumb), h.hotel_name, h.id, COUNT(c.id) as total_comments, SUM(c.rating) AS total_ratings
FROM 
at_hotels h 
LEFT JOIN 
at_gallery g 
ON 
h.id = g.h_id
LEFT OUTER JOIN
at_comments c
ON
h.id = c.h_id AND c.status = '1'
GROUP BY h.id, h.hotel_name
ORDER BY h.id DESC LIMIT 5

答案 1 :(得分:0)

首先,丢失DISTINCT - 不需要它 其次,格式化您的查询以使其可读,就像这种格式:

SELECT
  g.thumb,
  h.hotel_name,
  h.id,
  COUNT(c.id) as total_comments,
  SUM(c.rating) AS total_ratings
FROM at_hotels h 
LEFT JOIN at_gallery g ON h.id = g.h_id -- put join, tablee and on clause on same line
LEFT JOIN at_comments c ON h.id = c.h_id AND c.status = '1' -- removed OUTER: redundant
GROUP BY 1,2,3 
ORDER BY h.id DESC
LIMIT 5;

第三(已经在上面做过),将非聚合列添加到GROUP BY - 我更喜欢使用数字 - 它更清楚。

看看情况如何。

答案 2 :(得分:0)

我解决了这个问题。

问题是“评级”行DATA TYPE。

评级行数据类型为“SET”,值为1,2,3,4,5。

我将数据类型更改为TINYINT,记录会自动更改为:

5 -> 16
3 -> 4
5 -> 16

16 + 4 + 16 = 36

那么,总结'SET'数据类型是错误还是什么?