Mysql SUM 输出错误
我有一个这样的查询:
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
我的表:
I have a query like :
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
Query is working except SUM(rating). Sum command is giving more than expected. I also tried SUM command like this :
--query
(SELECT SUM(rating) FROM at_comments WHERE at_comments.h_id = at_hotels.id) AS total
--more query
and this is not worked too.
total must be : 13, but this is giving 36. Where is the problem?
Sample Data : (Comments Table)
id h_id rating
----------
1 | 1 |5
----------
2 | 1 |3
----------
3 | 1 |5
My Tables :
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
它完全取决于您的数据(我们看不到),但我建议不要依赖 MySQL 为您的分组做“正确的事情”,而是显式地对它们进行分组:
It's entirely dependent on your data (that we cannot see), but I'd suggest not relying on MySQL to do "the right thing" for your grouping, but to explicitly
GROUP BY
them:首先,丢失
DISTINCT
- 它是不需要的。其次,格式化您的查询,使其可读,就像这种格式一样:
第三(上面已经完成),将非聚合列添加到
GROUP BY
- 我更喜欢使用数字 - 它更清晰。看看情况如何。
Firstly, lose the
DISTINCT
- it isn't needed.Secondly, format your query so it is readable, like this kind of formatting:
Thirdly (already done above), add in non-aggregate columns to
GROUP BY
- I prefer using numbers - it's clearer.See how that goes.
我解决了这个问题。
问题在于“评级”行数据类型。
评级行数据类型为“SET”,值为 1、2、3、4、5。
我将数据类型更改为 TINYINT,记录会自动更改,如下所示:
那么,求和“SET”数据类型是否有问题?
I solved this problem.
The problem was the 'rating' row DATA TYPE.
Rating row datatype was 'SET' and the values 1,2,3,4,5.
I changed data type to the TINYINT, records are automatically changed like this :
So, summing 'SET' data type is buggy or something?