简体   繁体   English

不使用CAST的VARCHAR字段的mysql SUM

[英]mysql SUM of VARCHAR fields without using CAST

When SUM is used in query on field of type VARCHAR in MySql database, does SUM automatically convert it into number ? 当在MySql数据库中查询类型为VARCHAR的字段使用SUM时,SUM会自动将其转换为数字吗? I tried this by using 我通过使用尝试了这个

  SELECT SUM(parametervalue) FROM table

and it reveals that MySql returns the sum although I expected to throw it an error as "parametervalue" field is of VARCHAR type 并且它揭示了MySql返回总和,虽然我预计会抛出一个错误,因为“parametervalue”字段是VARCHAR类型

MySQL does silent conversion for a string in a numeric context. MySQL对数字上下文中的字符串进行静默转换。 Because it expects a number for the sum() , MySQL simply does the conversion using the leading "numbers" from a string. 因为它期望sum() ,所以MySQL只使用字符串中的前导“数字”进行转换。 Note that this include decimal points, minus sign, and even e representing scientific notation. 请注意,这包括小数点,减号,甚至代表科学记数法的e So, '1e6' is interpreted as a number. 因此, '1e6'被解释为数字。

In code, I personally would make the conversion explicit by adding 0 : 在代码中,我个人会通过添加0明确转换:

SELECT SUM(parametervalue + 0) FROM table

Ironically, the cast() might return an error if the string is not in a numeric format, but this doesn't return an error in that case. 具有讽刺意味的是,如果字符串不是数字格式,则cast()可能会返回错误,但在这种情况下,这不会返回错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM